You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言strremovestr函数存在内存泄漏,请求定位问题原因

内存泄漏位置分析

你的代码存在两处内存泄漏相关问题:

  • main函数未释放返回的动态内存
    strremovestr函数通过malloc和realloc分配内存并返回,但main函数中直接将返回值传入printf后,没有调用free释放这块内存,导致分配的内存无法回收,造成泄漏。

  • realloc调用的错误处理缺失导致泄漏风险
    代码中直接执行newdata=realloc(newdata,currsize + 1);,若realloc调用失败会返回NULL,此时原newdata指针会被覆盖为NULL,最初malloc分配的内存就会丢失,无法被释放,进而引发内存泄漏。

另外代码里还有个拼写错误:ewdata应为newdata,这个错误会导致程序行为异常,但不属于内存泄漏范畴。

修复示例

  1. 修复main函数的内存释放:
int main(){
    char* result = strremovestr("hello", "e");
    printf("%s\n", result);
    free(result); // 释放动态分配的内存
    return 0;
}
  1. 安全调用realloc:
// 替换原realloc行
char* temp_ptr = realloc(newdata, currsize + 1);
if (temp_ptr != NULL) {
    newdata = temp_ptr;
} else {
    // 分配失败时,先释放原内存再返回错误
    free(newdata);
    return NULL;
}
newdata[currsize] = '\0';

内容的提问来源于stack exchange,提问作者Lime Stone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:22:29