Search code examples
cdynamic-allocation

Macro with calloc, is safe?


is safe if I use this macro in my code?

#define my_calloc(x, n) ((x) = (__typeof__ (x))calloc((n), sizeof(__typeof__ (&(x)))))

I'm usign gcc as compiler...

In my programm there is a lot of memory allocation point, so I use this. I tried it 5 minutes ago and I get some weird sigabort and sigsev, now I'm going home... after I'll try again if I can find something.

Some idea/tip?

EDIT ADDED:

Generally I use the macro as follows:

double *x;
my_calloc(x, 10);

int **y;
my_calloc(y, 30);

Solution

  • I think it should probably be:

    #define my_calloc(x, n) do { (x) = calloc((n), sizeof *(x)); } while (0)
    
    • unnecessary/dangerous cast has been removed
    • redundant parentheses removed
    • do/while added for correct behaviour between if (...) and else
    • fixed size of type
    • remove redundant and non-portable __typeof__