这闻起来像是某种堆损坏,但我似乎找不到它。
尝试运行 free(tmp_for_free)
时,string_utils_replace()
上会出现此问题。该函数应该将 “string”
中每次出现的 “search”
替换为 “replace”
。
char* string_utils_part_of_string(char *string, int from, int to)
{
int size_to_allocate = to - from + 1;
char *result = (char*)malloc(sizeof(char) * size_to_allocate);
strncpy(result, string + from, to - from);
result[size_to_allocate - 1] = '\0';
return result;
}
char* string_utils_replace(char *search, char *replace, char *string)
{
char *end, *result = string, *tmp_for_free = NULL;
int before_replace, after_replace;
int size_search = strlen(search);
int size_replace = strlen(replace);
int size_string, size_find;
int first_time = 1;
char *find = strstr(string, search);
if (find == NULL)
return string_utils_copy_string(string);
while (find != NULL)
{
tmp_for_free = result;
size_string = strlen(result);
size_find = strlen(find);
before_replace = size_string - size_find;
after_replace = before_replace + size_replace;
end = string_utils_part_of_string(result, after_replace, size_string);
result = string_utils_part_of_string(result, 0, before_replace);
strcat(result, replace);
strcat(result, end);
// no memory leaks, hooray!
free(end);
if (first_time == 0)
free(tmp_for_free);
size_string = strlen(result);
find = strstr(result, search);
first_time = 0;
}
return result;
}
有什么想法吗?
最佳答案
根据 man page strcat()
,
char *strcat(char *dest, const char *src);
[..] and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable;
在您的string_utils_part_of_string()
函数中,您没有为结果
分配足够的内存来保存整个输入,并且稍后,您尝试通过 strcat()
使用同一指针来存储整个输入。这会造成内存溢出,进而调用 undefined behaviour .
注意:请do not cast C
中 malloc()
及其族的返回值。
关于c - 尝试释放时出现堆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918374/