safe malloc/realloc: wrapping the call into a macro?

c, macros, malloc

Solution

No, it's broken.

It seems to assume that the boolean or operator `||` returns its argument if it's deemed true, that's not how it works.

C's boolean operators always generate `1` or `0` as integers, they do not generate any of the input values.

Problem

I would like to wrap my calls to malloc/realloc into a macro that would stop the program if the method returns NULL can I safely use the following macro? ``` #define SAFEMALLOC(SIZEOF) (malloc(SIZEOF) || (void*)(fprintf(stderr,"[%s:%d]Out of memory(%d bytes)\n",__FILE__,__LINE__,SIZEOF),exit(EXIT_FAILURE),0)) char* p=(char*)SAFEMALLOC(10); ``` it compiles, it works here with `SAFEMALLOC(1UL)` and `SAFEMALLOC(-1UL)` but is it a safe way to do this?

Original source