How to check if a double pointer is NULL in the C language ?
I pass a double pointer how parameter of a function.
I need to check twice, like so ???
typedef struct no_t no_t;
struct no_t
{
no_t *prev;
no_t *next;
void *obj;
};
int32_t dynll_free_node_and_object(no_t **node)
{
if (node == NULL)
return -1;
if (*node == NULL)
return -2;
free((*node)->obj);
(*node)->obj = NULL;
(*node)->prev = NULL;
(*node)->next = NULL;
free(*node);
*node = NULL;
return 0;
}
That is one way to do it. Code risks invoking undefined behaviour if only
*nodewas checked (nodecould potentially beNULL), or if it was checked first (for the aforementioned reason).If the different return values only serves noise, consider returning -1 if either is
NULL:You may instead want to
abort()the program:Or perhaps simulate
free(NULL)by allowing aNULLpointer. It will be a NOP.Note that setting these pointers to
NULLlike so:is pointless because the subsequent assignment of
NULLto*nodeinvalidates it.*nodeno longer points to its original location, so the freed memory can not be accessed through it. (It's not your problem if the caller saved a copy of the original pointer and tried to access memory after it was freed). — @n.m.