Search code examples
c++cstrdup

risk with returning strdup from a function with return type as char *?


If I want to return strdup from a function whose return type is char*, then what are the risks or chances of memory leak ?

char* fun () {
    return strdup("hello");
}

int main() {
    for(;;)
    printf("%s\n", fun());
}

Solution

  • strdup() returns a pointer to newly-allocated memory that must be freed later with free(). You'll leak memory if you don't call free() on it — which, in your example, you don't.