Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when delete my_object; is executed? Is all other memory shifted to the left by sizeof(MyClass)?

For the sake of this question I will picture memory as a simple array of bytes, and I will be talking about heap memory because it is possible to dynamically allocate it.

Lets say that I am instantiating some class, and creating an object on the heap where some memory has already been allocated. Then, after creating the object, I allocate some more memory (maybe by instantiating another class). This implies the use of new and delete keywords, of course.

The memory now looks like this:

... byte byte my_object ... my_object byte byte ...

What exactly happens when delete my_object; is executed? Is all other memory shifted to the left by sizeof(MyClass)? If so, by who? The OS? Then what happens when there is no OS to provide virtual memory?

like image 838
corazza Avatar asked Jan 03 '13 20:01

corazza


3 Answers

No, nothing gets shifted. Instead, memory gets fragmented, meaning that you now have a unused hole in the middle of used memory. A subsequent allocation might be able to re-use part or all of that memory (provided the requested number of bytes is small enough to fit in the hole).

Some languages/environments support compacting garbage collectors. Such collectors are permitted to move objects around and can therefore eliminate holes if they choose to. Such approaches are complicated to implement since the collector needs to know the location of every single pointer within the program. Collectors of this type are therefore more suitable for higher-level languages.

like image 54
NPE Avatar answered Oct 22 '22 14:10

NPE


If the memory were shifted, that'd be a pretty bad OS IMO. Typically, the OS is notified that that memory is available for re-use. It's not even required to be cleared (and most of the time isn't). When no more memory can be allocated, you'd typically get an exception (if you're using new) or a NULL pointer back (if you're using malloc).

If fragmentation is a concern (it sometimes is), you'll have to write your own memory pool you can use (existing) memory pools which can deal with that, but even so, most of the responsibility still falls on the programmer.

like image 30
Luchian Grigore Avatar answered Oct 22 '22 12:10

Luchian Grigore


Memory is not shifted to the left. Imagine what would happen if it was. All those pointers "on the right" would become invalid.

like image 2
s.bandara Avatar answered Oct 22 '22 14:10

s.bandara