Search code examples
cmemorymemory-managementmemory-leaks

C program has memory leak


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.


Solution

  • 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
    • do not cast the result of malloc
    • store result of the realloc in temporary pointer. Otherwise if realloc fails, you will have another memory leak.
    • check the result of memory allocation functions.
    • newdata[currsize] = '\0'; strcpy copies null terminating character too. It is not needed