0

It is generally advised to assign NULL to a freed up pointer as otherwise it may lead to dangling pointer. I want to know if there is any case where not assigning NULL has some use?

If not, why is it not implemented in the call to 'free()' itself? I understand that the pointer is passed by value and thus cannot be modified. Could the function free() have been be implemented to accept pointer to a pointer(i.e reference to the pointer) where the pointer(not pointer to pointer) points to NULL in the end?

I am asking this since we have to always keep in mind about assigning NULL to pointer after freeing which is a very commonly called function(I am assuming).

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Subhodeep Maji
  • 100
  • 1
  • 10
  • 2
    Setting it to `NULL` (which is just `0`, by the way) takes CPU time. Sometimes it's simply not necessary (because you're not using the pointer anymore), so why force the program to waste a few split nanoseconds there? – Blaze Dec 05 '18 at 08:30
  • 1
    It's c. The main aim is to go fast. I often free a pointer only to malloc a bigger chunk of memory to the same variable immediatley – phil Dec 05 '18 at 08:31
  • 1
    if you don't like how `free()` and `delete` work, why not write a function or macro which extends it's functionality? `#define free2(x) (free(x); x=NULL;)` – Detonar Dec 05 '18 at 08:35
  • It's not in `C++` because it wasn't in `C`, it wasn't in `C` because references were not possible and `ptr = NULL` has a runtime cost. Effectively `free` would have to take a double ptr or be implemented as a macro in `C`. – George Dec 05 '18 at 08:36
  • Another option taken by Objective C with Zombies enabled is to keep the pointer and memory, but move it to another list and mark it as "released". When a program touches the memory associated with the "released" pointer then diagnostics flag the access and alert the programmer. – jww Dec 06 '18 at 03:01
  • Thank you all for your answers and different perspectives. I am satisfied with them :D – Subhodeep Maji Dec 06 '18 at 06:16

1 Answers1

1

Generally it's not for the code but us. cause free doesn't set the pointer to NULL, as if may be needed in some low level situation for some, and more generally the approach of C/C++ is to do things manually by programmer as if they may need specific requirements and this is one the being so pro of C/C++.

Anyway, by setting the pointer to NULL , now if it's happened to be used later in code now we can check if it's NULL or not, and this prevent from dangling and using unallocated memory pointers.

Setting variable to NULL after free

Why is my pointer not null after free?

https://www.quora.com/Why-should-we-assign-NULL-to-the-elements-pointer-after-freeing-them

https://www.acodersjourney.com/top-20-c-pointer-mistakes/

https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152148

nullqube
  • 2,959
  • 19
  • 18