What does free do with the pointer passed the value to the function?

It is known that if we pass a pointer by the value of a function, it cannot be freed inside the function, for example:

void func(int *p) { free(p); p = NULL; } 

p contains a copy of the (supposedly valid) address, so free (p) tries, well, to free it. But since this is a copy, she cannot really set her free. How does calling free () know that it really cannot free it?

There is no error in the above code. Does this mean that free () just fails, for some reason, knowing that the address passed as an argument cannot be processed?

+4
source share
5 answers

p contains a copy of the (supposedly valid) address, so free (p) tries, well, to free it. But since this is a copy, she cannot really set her free.

It is not true. free() may work fine if p is a valid address returned by malloc() (or NULL ).

In fact, this is a general template for implementing user-defined "destructor" functions (when writing OO-style code in C).

What you probably mean is that p will not change to NULL after that, but this is natural since you pass it by value. If you want free() and reject the pointer, then pass it with the pointer ("byref"):

 void func(int **p) { if (p != NULL) { free(*p); *p = NULL; } } 

and use it like

 int *p = someConstructor(); func(&p); // here 'p' will actually be NULL 
+16
source

The only problem is that this function is in another DLL (Windows). It can then be linked to another version of the standard library and have different ideas on how the heap is created.

Otherwise, no problem.

+2
source

Passing p to func() by value, which will copy the pointer and create a local copy in func() , which will free up memory. func() then sets its own instance of p to NULL , but is useless. At the end of the function, the parameter p ends. In the call function, you still have a pointer p containing the address, but the block is now in a free list and is not useful for storage until it is highlighted again.

+2
source

What everyone says is that your memory will be freed free(p); but your source pointer (which you use to call function c) will still contain the (now invalid) address. If a new block of memory, including your address, is allocated at a later stage than your original pointer becomes valid again (for the memory manager), but now it will point to completely different data, causing all kinds of problems and confusion.

+1
source

No, you really free the memory block. After calling the function, the pointer passed to this function points to nowhere: the same address, but the MMU no longer knows what to do with this address.

0
source

All Articles