I am writing a function to find variables in a string using regular expression. That functionality works fine, but when I try to free the temporary char* that holds the string I'm evaluating, glibc invokes with an invalid pointer error and the program aborts. In the code below, if the while loop is never entered, no crash occurs.
What am I doing incorrectly?
int parse_variables(size_t read_len) { regex_t comp_regex; int start = 0; char *command_copy = malloc(sizeof(command)); strcpy(command_copy, command); if (regcomp(&comp_regex, "[$][^0-9_][A-Z0-9_]+", REG_EXTENDED) != 0) { pmesg(1, "Regex compilation failed. Not parsing for variables.\n"); return -1; } regmatch_t pmatch; int var_match = regexec(&comp_regex, command_copy+start, comp_regex.re_nsub+1, &pmatch, 0); pmesg(1, "The initial value of var_match is %i.\n", var_match); while (var_match == 0) // We are finding instances matching the regex { int length = pmatch.rm_eo-pmatch.rm_so; char* var_name = malloc(length*sizeof(char)); strncpy(var_name, command_copy + start + pmatch.rm_so, length); pmesg(1, "The length is: %i - %i = %i.\n", pmatch.rm_eo, pmatch.rm_so, length); pmesg(1, "The variable's name is: %s.\n", var_name); free(var_name); start += pmatch.rm_eo; var_match = regexec(&comp_regex, command_copy+start, comp_regex.re_nsub+1, &pmatch, 0); } free(command_copy-start); return 0; }