c - 尝试释放时出现堆错误

标签 c strcat

这闻起来像是某种堆损坏,但我似乎找不到它。 尝试运行 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 Cmalloc() 及其族的返回值。

关于c - 尝试释放时出现堆错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29918374/

相关文章:

从 const char *src 到 char *dest 的 C 逐字符字符串操作

c - strcat() 实现有效,但最后导致核心转储

c - 获取指针错误引用的 strcpy 和 strcat 的实现

你能直接修改用户空间中inode的间接 block 吗?

c - 取消引用 C 中不完整类型的指针(指向结构的指针)

c - 如何在二维数组(多维数组)中使用 fgets()?

c - 修改传递给函数的 char 数组,C

c - 读取文本文件,复制到 C 中的数组

c - 为什么这个 scanf 会导致段错误?

c - 在 strcat 中添加空间