Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

macros

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?

like image 674
Pierre Avatar asked Apr 30 '13 10:04

Pierre


People also ask

Can you call realloc before malloc?

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.

What happens if you call malloc 0?

malloc(0) does not allocate any memory.

How many arguments can calloc take?

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.


2 Answers

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__)
like image 124
Jim Balter Avatar answered Oct 18 '22 22:10

Jim Balter


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.

like image 25
unwind Avatar answered Oct 18 '22 21:10

unwind