Xis88 Xis88 - 1 year ago 52
C Question

Is ptr = free(ptr), NULL safe?

I'm writing code like this:

#include <stdlib.h>

int main(void)
void *kilobyte;
kilobyte = malloc(1024);
kilobyte = NULL, free(kilobyte);
return 0;

for symmetry, which is nice. But I've never seen anyone else using this idiom before, so I wonder if this might actually be unportable/unsafe, despite this Wikipedia quote:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

Edit: mixed up the order. Now it compiles on
without any warnings.

Answer Source

By doing this:

kilobyte = NULL, free(kilobyte);

You have a memory leak.

You set kilobyte to NULL, so whatever memory it was pointing to is no longer referenced anywhere. Then when you do free(kilobyte), you're effectively doing free(NULL) which performs no operation.

Regarding free(NULL), from the C standard. The free function


#include <stdlib.h>
void free(void *ptr);

2. The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

What you probably want to do is this:

kilobyte = (free(kilobyte), NULL);

This frees the pointer, then sets the pointer to NULL.

The problem with what you had before is than = has higher precedence than ,, so your original expression was effectively (kilobyte = free(kilobyte)), NULL; which tried to set a variable to void which is not allowed.