1
int main(){

(int*) pointer = (int*) malloc(sizeof(int));
free(pointer);

}

I learned from 'Prata, Stephen. C Primer Plus (Developer's Library)' that "When the function terminates, the pointer, being an automatic variable, disappears." so simply, i don't need to null the pointer

however, I also learned from school that the pointer becomes a dangling pointer if it doesn't get nulled after it free.

Two ideas are contradicting each other. Which one is the right one?

NutCracker
  • 11,485
  • 4
  • 44
  • 68
  • `pointer` is a dangling pointer, but what does it matter? It goes out of scope right after anyway. – Blaze Feb 17 '20 at 08:23
  • 1
    Dangling pointers are not a problem, as long as you don't use them. You can have a dangling pointer in a variable, and then reuse the variable to point somewhere else. – Some programmer dude Feb 17 '20 at 08:23
  • For what I know, setting it to null is a kind of "safe" gate, so that later you can still use it in comparison without having memory errors with ```if (pointer == null)``` – Angevil Feb 17 '20 at 08:24
  • you need to free the pointer,. that's the better approach – Murtaza Ahmad Feb 17 '20 at 08:27
  • 2
    [Should one really set pointers to `NULL` after freeing them?](https://stackoverflow.com/questions/1879550/should-one-really-set-pointers-to-null-after-freeing-them), and literally at least a dozen others on a similar line. – WhozCraig Feb 17 '20 at 08:28

2 Answers2

3

According to the docs:

The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Therefore, you don't need to set pointer to nullptr (in C++11) or NULL (in C and before C++11) if it goes out of scope immediately after you free it because then you have no chance to dereference a dangling pointer.

However, if the pointer is still in the scope after a call to free, than the good practice would be to set it to nullptr or NULL so that the following checks would work:

C++:

if (nullptr != ptr) {...}

C:

if (NULL != ptr) {...}

C and C++:

if (!ptr) {...}
NutCracker
  • 11,485
  • 4
  • 44
  • 68
0

What free does is to deallocate the space that pointer holds before the execution of free. The pointer holds an integer value(the address) before and after the execution therefore the address that the pointer holds is now an invalid address that is not allocated by the program. As said, if you plan to use the pointer again in future cases, you wouldn't wanna have an invalid undefined value in it that you cannot check, having null makes the checks easier.