Question

I want to write macro in c code to freeing many pointers like this :

FREE(ptr1, ptr2, ptr3, ptr4, ptrx);

For me, this is better than

 FREE(ptr1); 
 FREE(ptr2);
 FREE(ptr3);
 FREE(ptr4);
 FREE(ptrx);

Thanks in advance

Regards,

Was it helpful?

Solution 2

You can pass variable number of arguments in macro. Following code works fine:

#define FREE_ALL(...) \
do { \
    int i=0;\
    void *pta[] = {__VA_ARGS__}; \
    for(i=0; i < sizeof(pta)/sizeof(void*); i++) \
    { \
        free(pta[i]); \
    }\
} while(0)

OTHER TIPS

Use a function with variable number of function arguments. Header: stdarg.h.

I had a little fun with the solution.

#define FREE( ... ) Free( &free_stop , __VA_ARGS__ , &free_stop )
//takes any number of pointer arguments,(at least one )( can also take NULL which is handled by free )

int free_stop ;

void Free( void* point , ... )  
{
    if( !point )
        return ;

    va_list list ;
    va_start( list , point ) ;

    void* p = va_arg( list , void* ) ;
    while( p != point ) 
    {
        free( p ) ;
        p = va_arg( list , void* ) ;
    }


    va_end( list ) ;

}

Usage:

FREE( ptr1 , ptr2 , ptr3 ) ;   //don't have to NULL terminate

Maybe you can define a function like:

void freeargs(void *ptr1, ...) {
    // code for freeing variable number of arguments until NULL pointer.
}

and then the macro:

#define FREE(...) freeargs(__VA_ARGS__, NULL)

I think it's a neutral idea. positive:If you want to free pointers together,it can help.but it seemly doesn't save much things. negative:if the pointers may free dispersedly,then you should wait them used,which may cause pointers fogetten. by the way,the macos can be

#define FREE(ptr1, ptr2, ptr3, ptr4, ptrx) (free(ptr1);free(ptr2);free(ptr3);free(ptr4);free(ptr5);)

use BOOST

#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/tuple/to_seq.hpp>

#define PROC(r, f, elem) f(elem);
#define FREE(...) BOOST_PP_SEQ_FOR_EACH(PROC, free, BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top