Search code examples
cpointersfreec-standard-library

How to determine whether a return char pointer needs to be free in C standard library functions?


I've little experience in C program developing. As I described in the title, how to determine whether a return char pointer needs to be free in C standard library functions? For examples, do I need to free the return pointer of function getenv in stdlib.h and strstr in string.h? I can't find any description in the document.

Thanks in advance.


Solution

  • http://en.cppreference.com/w/cpp/utility/program/getenv

    Modifying the string returned by getenv invokes undefined behavior.

    So you shouldn't touch that one.

    http://en.cppreference.com/w/cpp/string/byte/strstr

    Return value: Pointer to the first character of the found substring in str

    This returns a pointer to a character within the input c-string. So it's a pointer to memory that already existed, not a newly allocated string, and you shouldn't free it.

    p.s. Though it doesn't change the answer, I took the perspective of the C++ tag of the question. For C language documentation see the manual pages or, for this website, http://en.cppreference.com/w/c/program/getenv and http://en.cppreference.com/w/c/string/byte/strstr (that have essentially the same content as the above)