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

StackOverflow https://stackoverflow.com/questions/14146298

  •  12-01-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

On a typical implementation (without a moving garbage collector for instance) nothing will be moved.

Bames53 says that Herb Sutter says that the standard says that automatic movement of allocated objects is illegal. Thanks Bames53.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top