how to freeing pointers using macro in c

前端 未结 5 634
我寻月下人不归
我寻月下人不归 2021-01-16 06:26

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

相关标签:
5条回答
  • 2021-01-16 06:33

    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
    
    0 讨论(0)
  • 2021-01-16 06:35

    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)
    
    0 讨论(0)
  • 2021-01-16 06:43

    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__)))
    
    0 讨论(0)
  • 2021-01-16 06:44

    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)
    
    0 讨论(0)
  • 2021-01-16 06:50

    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);)
    
    0 讨论(0)
提交回复
热议问题