free(): double free detected in tcache 2

确保返回值类型为非void的函数均含有 return 语句,否则将该函数的返回值类型改为void类型

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这个错误通常是因为重复释放了同一个指针所导致的。在你的代码中,出现这个错误的可能原因是:在调用 `replaceChar()` 函数之后,由于你在函数中使用了 `realloc()` 函数重新分配了 `str` 指向的内存空间,而在 `main()` 函数中,你使用 `free()` 函数释放了 `buf` 指向的内存空间,这就导致了重复释放同一个指针的错误。 解决这个问题的方法是:在 `replaceChar()` 函数中不要直接修改 `str` 指针的值,而是应该返回一个新的指针,指向重新分配的内存空间。在 `main()` 函数中,你就可以释放这个新的指针所指向的内存空间,而不会出现重复释放的问题。修改后的代码示例如下: ``` char* replaceChar(char* str, char chr, char* new_str) { int old_len = strlen(str); int new_len = strlen(new_str); int count = 0; char* p = str; while (*p != '\0') { if (*p == chr) { count++; } p++; } if (count == 0) { return str; } int new_size = old_len + count * (new_len - 1); char* new_str_ptr = (char*)realloc(str, new_size + 1); if (new_str_ptr == NULL) { return str; } str = new_str_ptr; char* dst = str + old_len + count * (new_len - 1); char* src = str + old_len; while (src >= str) { if (*src == chr) { memcpy(dst - new_len + 1, new_str, new_len); dst -= new_len; } else { *dst = *src; dst--; } src--; } return str; } int main() { char* buf = strdup("hello123456"); printf("buf=%s\n", buf); buf = replaceChar(buf, 'o', "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); printf("buf=%s\n", buf); free(buf); return 0; } ``` 在修改后的代码中,`replaceChar()` 函数返回一个新的指针 `new_str_ptr`,指向重新分配的内存空间,而不是直接修改原来的指针 `str` 的值。在 `main()` 函数中,你使用新的指针 `buf` 来指向 `replaceChar()` 函数返回的内存空间,这样就可以避免重复释放同一个指针的错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

<lumen>

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值