Wednesday, July 25, 2018

When memory deallocation is strictly required in C and C++?

I have found the following references to C and C++ standards in StackOverflow (Memory Allocation/Deallocation?), in relationship to memory deallocation:



C++ Language:



"If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage". [Bold is mine].



C Language:



The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. [Bold is mine].




So, let's suppose a scenario like the following one:



You have a linked list, in a demo app. After creating and linking your nodes, searching, sorting, and so forth, your app is finishing successfully, with a beautiful "return 0".



Which is the problem if you have not deallocated any node since all the pointers you have created have already been destroyed?



Please, I want to clearly distinguish between:




  • what is really needed ("If you do not deallocate you have a leak of memory because of....);



  • what is a good practice, but not strictly required.




Finally: intentionally, I have avoided mentioning smart pointers. Because, if your answer is "deallocating it is a good practice ( = not strictly required, no memory leak), because in a real life scenario you will need to deallocate, etc.", then I can conclude:




  • If I am developing a demo app, I do not need either to use a smart pointer (if I am in C++).


  • If I am in C, I do not need to deallocate, because while arriving at app end of scope, every pointer will be deleted.





Exception: if in my linked list, I have a function to delete nodes, then I understand I need to deallocate, because of memory leak.



Any advice, correction, clarification, distinction from your side will be very much appreciated!






Edit: Thanks to all for your quick answers. Specially @Pablo Esteban Camacho.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...