我正在寫一個函數來使用正則表達式在字符串中查找變量。該功能工作正常,但是當我嘗試釋放臨時字符*,其中包含我正在評估的字符串時,glibc會調用一個無效的指針錯誤,程序將中止。在下面的代碼中,如果while循環從未輸入,則不會發生崩潰。C free()調用中的無效指針
我在做什麼不正確?
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;
}
感謝您的更正。 – 2011-02-07 02:54:10