I have made a function in C called strremovestr
to remove substring from string, but there's a memory leak.
#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;
}
Now this is reproducible example, you can run with valgrind to confirm that it has memory leak. I had to add spacing between things in this code to make it more easier to read :)
Where's the memory leak here? Thanks for reading.
You allocate the memory
char* newdata=(char*)malloc(currsize+1);
but you never free it.
int main()
{
char *str;
printf("%s\n",(str = strremovestr("hello", "e")));
free(str);
}
also:
strlen
returns size_t not int
malloc
realloc
in temporary pointer. Otherwise if realloc
fails, you will have another memory leak.newdata[currsize] = '\0';
strcpy
copies null terminating character too. It is not needed