C 程序存在内存泄漏

问题描述 投票:0回答:1

我在 C 中做了一个名为

strremovestr
的函数来从字符串中删除子字符串,但是存在内存泄漏。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* strremovestr(const char* data,const char* what){
    const int ws = strlen(what);
    const int ds = strlen(data);
    size_t currsize = ds;
    char* newdata=(char*)malloc(currsize+1);
    strcpy(newdata, data);
    newdata[currsize] = '\0';
    const char* hehe = NULL;
    while((hehe=strstr(newdata, what))){
        size_t detent = hehe - newdata;
        memmove(newdata+detent, ewdata + detent + ws,currsize - detent - ws+ 1);
        currsize-=ws;
    }
    newdata=realloc(newdata,currsize + 1);
    newdata[currsize] = '\0';
    return newdata;
}
int main(){
    printf("%s\n",strremovestr("hello", "e"));
    return 0;
}

现在这是可重现的示例,您可以使用 valgrind 运行来确认它是否存在内存泄漏。 我必须在这段代码中的内容之间添加间距,以使其更易于阅读:)

这里的内存泄漏在哪里?感谢您的阅读。

c memory memory-management memory-leaks
1个回答
1
投票

你分配内存

char* newdata=(char*)malloc(currsize+1);

但你永远不会释放它。

int main()
{
    char *str;
    printf("%s\n",(str = strremovestr("hello", "e")));
    free(str);
}
© www.soinside.com 2019 - 2024. All rights reserved.