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?
malloc is not required, you can use realloc only. malloc(n) is equivalent to realloc(NULL, n) . However, it is often clearer to use malloc instead of special semantics of realloc . It's not a matter of what works, but not confusing people reading the code.
malloc(0) does not allocate any memory.
malloc() takes a single argument, which is the number of bytes to allocate. Unlike malloc(), calloc() takes two arguments: 1) Number of blocks to be allocated. 2) Size of each block in bytes.
static void* safe_malloc(size_t n, unsigned long line)
{
void* p = malloc(n);
if (!p)
{
fprintf(stderr, "[%s:%ul]Out of memory(%ul bytes)\n",
__FILE__, line, (unsigned long)n);
exit(EXIT_FAILURE);
}
return p;
}
#define SAFEMALLOC(n) safe_malloc(n, __LINE__)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With