It is known that if we pass a pointer by value to a function, it cannot be freed inside the function, like so:
void func(int *p)
{
free(p);
p = NULL;
}
p holds a copy of a (presumably valid) address, so free(p) tries to, well, free it. But since it is a copy, it cannot really free it. How does the call to free() know that it cannot really free it ?
The code above does not produce an error. Does that mean free() just fails silently, “somehow” knowing that address passed in as argument cannot be worked upon ?
It’s not true.
free()can work just fine ifpis a valid address returned bymalloc()(orNULL).In fact, this is a common pattern for implementing custom “destructor” functions (when writing OO-style code in C).
What you probably mean is that
pwon’t change toNULLafter this – but that’s natural, since you’re passing it by value. If you want tofree()and null out the pointer, then pass it by pointer (“byref”):and use this like