Let's say a have a function which takes in a buffer for something, and may need to allocate the memory to the buffer in the function's scope. It might look like this:
void func_with_buf( ...params..., char** buf ) {
if ( !buf ) {
buf = ( char** )calloc( ... );
}
/* more stuff here */
...
}
Now, later on in this function there be another conditional statement which evaluates to false, and if false is returned in the if/conditional statement, the buf
pointer-to-pointer should be freed, since nothing can be done further more in the function itself.
So, there are two approaches to this, and I'd like to know which one would be considered "safer" and more pragmatic in terms of extensibility, reuse, etc.
Approach A)
char* buf;
if ( !func_with_buf( ..., &buf ) ) {
free( buf );
buf = NULL;
/* more error handling here */
}
Approach B)
char* buf;
if ( !func_with_buf( ..., &buf ) ) {
/* no need to free buf because func_with_buf handles deallocation internally. */
}
Something tells me that approach A) would be the recommended way to go, but I'm curious and would like to see if I've over looked anything.
Also, if the programmer needs to free a pointer-to-pointer, is it as simple as just passing it to free(p)
and it will handle it? Or do I need to cast it to a single pointer of the same type?
So many questions...