Reputation: 493
Just to achieve clarity in my project, i want to avoid using free(3)
in this manner:
free(ptr1);
free(ptr2);
.
.
.
free(ptrn);
So i had added a macro in this fashion
#define stop_point NULL
#define free_space(...){ \
void *ptrs[] = {__VA_ARGS__,stop_point}; \
for(int i=0;ptrs[i]!=stop_point;i++) free(ptrs[i]);}
And using it as following:
free_space(ptr1,ptr2,...ptrn);
I think this mechanism works but there is one problem, e.g. in the above line, if ptr2
is NULL, then other pointers following ptr2
(i.e. ptr3,ptr4...) will not get free
.
What i need is a better stop_point
. How can i achieve that ?
Thank you.
Upvotes: 0
Views: 64
Reputation: 223329
Use a different sentinel. Change the macro to:
#define free_space(...) { \
void *ptrs[] = { __VA_ARGS__, ptrs }; \
for (int i = 0; ptrs[i] != ptrs; i++) free(ptrs[i]); }
or use the length of the array created from the list:
#define free_space(...) { \
void *ptrs[] = { __VA_ARGS__ }; \
for (size_t i = 0; i < sizeof ptrs / sizeof *ptrs; i++) free(ptrs[i]); }
Upvotes: 3