I think your idea that the "many" functions in POSIX return pointers is thus erroneous. Your example, inet_ntoa not in POSIX , and was deliberately excluded because it is deprecated and broken.
The number of standard functions that return pointers to allocated memory is actually quite small, and most of them provide a special additional function that you should use to free memory (for example, fopen and fclose , getaddrinfo and freeaddrinfo , or regcomp and regfree ). Just calling free on the returned pointer would be very bad; in the best case, you will encounter serious memory leaks, and in the worst case, it can lead to unexpected failures (for example, if the library stores objects that it places in a linked list).
Regardless of whether the function is part of a system library or a third-party library, it should document the expected use of any pointers that it returns (and regardless of whether they need to free them). For standard functions, the best reference to this question is POSIX itself . You can also check the manual pages for your specific system. If the code is part of a third-party library, it should contain documentation (possibly on the manual pages, in header files, or in the complete document on using the library). A well-written library will provide special functions for the free objects that it allocates to avoid introducing dependencies on how it is (currently) implemented for code that uses the library.
As for non-standard inet_ntoa and similar obsolete functions, they return pointers to internal static buffers. This makes them unsuitable for use with streams or in library code (which should take care not to destroy the state of the caller if it is not documented). Often, the documentation for such functions says that they are not required for thread safety , that they are not reentrant, or that they can return a pointer to an internal static buffer that can be overwritten by subsequent calls to the function. Many people, including myself, believe that such functions should not be used at all in modern code.
R ..
source share