how to freeing pointers using macro in c

前端 未结 5 633
我寻月下人不归
我寻月下人不归 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
    

提交回复
热议问题