I received this message:
expected 'void **' but argument is of type 'char **'
when I tried to compile something similar to this:
void myfree( void **v ) { if( !v || !*v ) return; free( *v ); *v = NULL; return; }
I found that I think this solution after reading this stack overflow question:
Avoid incompatible pointer warnings when working with double direction - Stack Overflow
So I adapted to something like this:
#include <stdio.h> #include <stdlib.h> void myfree( void *x ) { void **v = x; if( !v || !*v ) return; free( *v ); *v = NULL; return; } int main( int argc, char *argv[] ) { char *test; if( ( test = malloc( 1 ) ) ) { printf( "before: %p\n", test ); myfree( &test ); printf( "after: %p\n", test ); } return 0; }
Is this legal C? I'm looking for a pointer to the void, right?
Thanks guys,
EDIT 10/12/2010 16:45 EST:
As stated, free(NULL) is safe and covered by the C standard. Also, as discussed below, my example above is not legal. See Answers in the cafe, Zack's answer and my own answer.
Therefore, it will be easier for me to initialize any to-be-malloc'd pointers as NULL, and then later just release () and NULL directly in the code:
free( pointer ); pointer = NULL;
The reason I checked NULL in myfree (), like me, was because of my experience with fclose (). fclose(NULL) may segfault depending on the platform (e.g. xpsp3 msvcrt.dll 7.0.2600.5512), and so I assumed (erroneously) the same thing could happen with free (). I figured out rather than cluttering up my code if I could better implement the function.
Thank you all for a good discussion.
c type-conversion compiler-warnings void-pointers void
Anonymous Question Guy
source share