Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any heap compaction in C++?

I have a notion that C++ runtime doesn't do any heap compaction which means that the address of an object created on heap never changes. I want to confirm if this is true and also if it is true for every platform (Win32, Mac, ...)?

like image 255
HS. Avatar asked Dec 09 '09 09:12

HS.


1 Answers

The C++ standard says nothing about a heap, nor about compaction. However, it does require that if you take the address of an object, that address stays the same throughout the object's lifetime.

A C++ implementation could do some kind of heap compaction and move objects around behind the scenes. But then the "addresses" it return to you when you use the address-of operator, are not actually memory addresses but some other kind of mapping.

In other words, yes, it is safe to assume that addresses in C++ stay the same while the object you're taking the address of lives.

What happens behind the scenes is unknown. It is possible that the physical memory addresses change (although common C++ compilers wouldn't do this, it might be relevant for compilers targeting various forms of bytecode, such as Flash), but the addresses that your program sees are going to behave nicely.

like image 99
jalf Avatar answered Oct 03 '22 07:10

jalf