我在 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 运行来确认它是否存在内存泄漏。 我必须在这段代码中的内容之间添加间距,以使其更易于阅读:)
这里的内存泄漏在哪里?感谢您的阅读。
你分配内存
char* newdata=(char*)malloc(currsize+1);
但你永远不会释放它。
int main()
{
char *str;
printf("%s\n",(str = strremovestr("hello", "e")));
free(str);
}