Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check deallocation of memory

How to check if memory to which pointer p points has been succesfully deallocated?

like image 430
There is nothing we can do Avatar asked Nov 10 '10 10:11

There is nothing we can do


People also ask

What is deallocation of memory?

Deallocation of memory by the Operating System (OS) is a way to free the Random Access Memory (RAM) of finished processes and allocate new ones. We all know that the computer memory comes with a specific size.

Which command is used for allocation and deallocation of the memory?

How is memory allocated/deallocated in C++? C uses the malloc() and calloc() function to allocate memory dynamically at run time and uses a free() function to free dynamically allocated memory.

What is deallocation of memory in C++?

In C++ when we want to allocate memory from the free-store (or we may call it heap) we use the new operator. int *ptr = new int; and to deallocate we use the delete operator.

How does free know how much memory to deallocate?

When we use the dynamic memory allocation techniques for memory allocations, then this is done in the actual heap section. It creates one word larger than the requested size. This extra word is used to store the size. This size is used by free() when it wants to clear the memory space.


2 Answers

Exception handling. I.e. try/catch blocks.

like image 143
mark j s Avatar answered Oct 12 '22 13:10

mark j s


In few words: you can't.

Check out tools like Valgrind to help you debugging memory leaks issues.

Some other things you should consider:

  • Use smart pointers so that you don't have do think about memory management,
  • Set your pointers to 0 after you free them, so that a further delete has no effect,
  • Use standard classes (vector, ...) instead of rolling your own,
  • Finally, don't use pointers (actually you almost can)
like image 23
Alexandre C. Avatar answered Oct 12 '22 12:10

Alexandre C.