尝试释放时出现堆错误

Getting a heap error when trying to free

这闻起来像是某种堆损坏,但我似乎找不到它。 尝试 运行 free(tmp_for_free) 时,问题出现在 string_utils_replace() 上。该函数应该用 "string".

中的 "replace" 替换每次出现的 "search"
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] = '[=10=]';

    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;
}

有什么想法吗?

您在这里造成了缓冲区溢出:

    result = string_utils_part_of_string(result, 0, before_replace);
    strcat(result, replace);
    strcat(result, end);

result 恰好分配了 before_replace+1 字节,并从 string 的开头和最后的 '[=15=]' 初始化为 before_replace 字节。您不能将 replaceend 连接到此数组,它已经满了。

你函数中的逻辑很复杂。你应该简化它。例如,您应该首先 运行 一个循环,计算 stringfind 的出现次数,然后为结果分配一个缓冲区,然后 运行 第二个循环复制片段string 的副本和 replace 的副本。

您还应该测试 find 是否为空字符串。 strstr() 总是会找到空字符串,导致你的算法无限循环。

根据 strcat()man page

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() 函数中,您没有为 result 分配足够的内存来保存 整个 输入,后来,您通过 strcat(),我们正在尝试使用相同的指针来存储 整个 输入。这会造成内存溢出,进而调用 undefined behaviour.

注:请do not castmalloc()和家人C的return值。