malloc/free
See this example
1 | char ** backtrace_symbols (void *const *buffer, int size) |
The return value of backtrace_symbols is a pointer obtained via the malloc function, and it is the responsibility of the caller to free that pointer. Note that only the return value need be freed, not the individual strings.
Question: Why does it say “only the return value need be freed, not the individual strings”?
Let us observe the defintion of the malloc
/free
functions first:
1 | void *malloc( size_t size ); |
free
takes a void*
pointer to deallocate the memory, it doesn’t care what type it is, even if it is a multi-level pointer. It means that malloc
has stored the memory size in some place and free
will find it beforing deallocate the memory.
Let us return the question. The memory pointer returned by backtrace_symbols
is the char**
type, it must be a whole block contigunous memory using malloc
and might be enforced to be transformed as char**
pointer when returing. So when we free
the memory block, the Linux kernel find its actual memory size and deallocate it.
Example:
1 |
|
More elegant but less economical code:
1 |
|