Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a third-party C function returns a pointer, should you free it yourself?

There are many functions (especially in the POSIX library) that return pointers to almost-necessarily freshly allocated data. Their manpages don't say if you should free them, or if there's some obscure mechanism at play (like returning a pointer to a static buffer, or something along these lines).

For instance, the inet_ntoa function returns a char* most likely out from nowhere, but the manpage doesn't say how it was allocated. I ended up using inet_ntop instead because at least I knew where the destination allocation came from.

What's the standard rule for C functions returning pointers? Who's responsible for freeing their memory?

like image 228
zneak Avatar asked Sep 05 '10 21:09

zneak


2 Answers

You have to read the documentation, there is no other way. My man page for inet_ntoa reads:

The string is returned in a statically allocated buffer, which subsequent calls will overwrite.

So in this case you must not attempt to free the returned pointer.

like image 189
CB Bailey Avatar answered Sep 23 '22 05:09

CB Bailey


There really isn't a standard rule. Some functions require your to pass a pointer in, and they fill data into that space (e.g., sprintf). Others return the address of a static data area (e.g., many of the functions in <time.h>). Others still allocate memory when needed (e.g., setvbuf).

About the best you can do is hope that the documentation tells you what pointers need to be freed. You shouldn't normally attempt to free pointers it returns unless the documentation tells you to. Unless you're passing in the address of a buffer for it to use, or it specifies that you need to free the memory, you should generally assume that it's using a static data area. This means (among other things) that you should assume the value will be changed by any subsequent calls to the same routine. If you're writing multithreaded code, you should generally assume that the function is not really thread-safe -- that you have a shared data area that requires synchronization, so you should acquire a lock, call the function, copy the data out of its data area, and only then release the lock.

like image 30
Jerry Coffin Avatar answered Sep 26 '22 05:09

Jerry Coffin