Dave Stafford said:
I have a macro that I use across the board for freeing ram. I'd like to
clean up my code so I don't get these warnings.
#define sfree(x) _internal_sfree((void **)&x)
#define _internal_sfree(x) ({ if(x && *x) { free(*x); *x=NULL; } })
void main() {
char *x = (char *) malloc(10);
int *y = (int *) malloc(10);
sfree(x);
sfree(y);
}
results in:
warning: dereferencing type-punned pointer will break strict-aliasing
rules
Your macro depends on a gcc-specific extension (see "Statement Exprs"
in the gcc manual).
You take care to avoid passing a null pointer to free(), but
free(NULL) is guaranteed to do nothing.
Take a look at the following version of your program.
================================
#include <stdlib.h>
#define SFREE(p) (free(p), (p) = NULL)
int main(void) {
char *x = malloc(10);
int *y = malloc(10 * sizeof *y);
SFREE(x);
SFREE(y);
return 0;
}
================================
Every change I made fixes a bug in your code:
main() returns int, not void. And since it returns int, you should
return an int.
I renamed the macro from "sfree" to "SFREE"; by convention, most
macros should have all-caps names.
In a macro definition, references to arguments should be enclosed in
parentheses to avoid operator precedence problems.
Casting the result of malloc() is useless, and can hide bugs.
You didn't have a '#include <stdlib.h>'. This is required if you're
going to call malloc(). The casts probably silenced your compiler's
warning about this, but didn't fix the bug (it's like snipping the
wire to a warning light on your car's dashboard).
Allocating 10 bytes for an int* doesn't make much sense if, for
example, sizeof(int) == 4. I changed it to allocate 10 ints.
Recommended reading: the comp.lang.c FAQ, <
http://www.c-faq.com/>.