Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nonnull argument compared to NULL in C

Tags:

c

memory

malloc

In the following function designed to free some memory allocated to a pointer of type Maze with Maze being a struct I defined in another file.

I am getting the compiler error nonnull argument 'maze' compared to NULL This is just a warning but I am constrained to leave the warning turned on.

Here is the code for the function:

void free_maze(Maze *maze) {
    if (maze == NULL) {
        return;
    }

    free(maze);
    return;
}

As I understood, this is the correct way to check if a pointer to a struct is NULL. What am I doing wrong here?

like image 465
Colin Harrison Avatar asked Sep 12 '25 00:09

Colin Harrison


1 Answers

The reason of the warning is probably that the declaration of free_maze looks similar to this:

extern void free_maze (Maze *maze)
        __attribute__((nonnull));

__attribute__((nonnull)); is a GCC-specific extension.

So the declaration says that NULL should never be passed to free_maze. The compiler will try to detect violations of this constraint and warn you. Since you are not supposed to pass NULL, it makes little sense to check for it.

Even without an attribute, you don't need to check because free(NULL) is guaranteed to be safe.

Regarding your edit: a call

free(maze);

doesn't change maze in the scope of the caller. If you accidentally call free once again with the same pointer, the second call will not be with NULL but with a dangling pointer, leading to undefined behaviour. Just don't do double-free.

like image 118
n. 1.8e9-where's-my-share m. Avatar answered Sep 13 '25 15:09

n. 1.8e9-where's-my-share m.