Search code examples
c++cglibc

What kind of returned value from glibc functions needs to be free()d?


As we know all dynamically allocated memories need to be freed using free() by the programmer himself. For the variables which the programmer himself creates and allocates memory to them almost there is not a problem as he knows what to call free() for. But what about pointers returned from glibc functions like getenv(). At first I thought I needed to free the memory pointed by the result of getenv() but then noticed the man says:

As typically implemented, getenv() returns a pointer to a string within the environment list.The caller must take care not to modify this string, since that would change the environment of the process

This means the function getenv() hasn't called malloc() to create a new space for the string whose address is returning. So which of the pointers returned from these functions explicitly needs to be freed?


Solution

  • So which of the pointers returned from these functions explicitly needs to be freed?

    The ones that the man page tells you to free, and only these.

    Pointers returned by getenv, fopen, strstr, memcpy and many others should not be free()d (for obvious reasons: just read their man pages).