I want a macro to free multiple (variadic number) pointers of different type. Based on similar questions in SO I made this code which seems to work
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
/* your compiler may need to define i outside the loop */
#define FREE(ptr1, ...) do{\
void *elems[] = {ptr1, __VA_ARGS__};\
unsigned num = sizeof(elems) / sizeof(elems[0]);\
for (unsigned i=0; i < num; ++i) free(elems[i]);\
} while(0)
int main(void)
{
double *x = malloc(sizeof(double)); /* your compiler may need a cast */
int *y = malloc( sizeof(int)); /* ditto */
FREE(x, y);
}
My question is
- Is the creation of a
void*
array correct in this context? (I saw the same trick with*int[]
, so the question is will a*void[]
do what I expect) - Is the code C99 compliant, are there any compilers that would have problems with this?