Search code examples
cmemory-leaksstrdup

strdup() causing memory leaks?


I've implemented a function that returns a string. It takes an integer as a parameter (age), and returns a formatted string.

All is working well, except from the fact that I have some crazy memory leaks. I know strdup() is the cause of this, but I've tried to research some fixes to no avail.

My code is:

const char * returnName(int age) {

    char string[30];

    sprintf( string, "You are %d years old", age);

    return strdup(string);
}

Valgrind's output is:

==15414== LEAK SUMMARY:
==15414==    definitely lost: 6,192 bytes in 516 blocks
==15414==    indirectly lost: 0 bytes in 0 blocks
==15414==      possibly lost: 0 bytes in 0 blocks
==15414==    still reachable: 0 bytes in 0 blocks
==15414==         suppressed: 0 bytes in 0 blocks

Any help in resolving this memory leak issue is greatly appreciated.


Solution

  • From man strdup:

    Memory for the new string is obtained with malloc(3), and can be freed with free(3).

    So you need to free the space allocated and returned by strdup.

    Say you invoke returnName like that:

     const char* str = returnName(3);
    

    After you're done with str you can free it like this:

    free((char*) str);
    

    The cast is needed because free expects a non-const void*. This explicit conversion is alright here because returnName actually should return constant data1. Calling free is only a nasty implementation detail here.


    1 As discussed with @M.M in the comments to this answer.