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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With