x4rkz
x4rkz

Reputation: 523

Assembly - Heap alignment - x86 intel

I think I understood stack alignment which is 4-bytes, for example if I add one only char, his address will be at the right of the 4 bytes (a little before if there are other 1 or 2 bytes variables)

Still I can't understand the alignment in the heap, I thought there was 4-bytes or 8 bytes alignment but here's the thing, when I allocate 100 then 20 bytes, there are 4 bytes between the end of the first one and the beginning of the second, so I guessed that the heap would use 8bytes alignment.

By consecutivly allocating 1 4 7 8 9 14 16 17 bytes I noticed that 1, 4, 7, 8, 9 take 16 bytes each and 14 16 17 take 24 bytes, why so ?

I am using C/C++ and using malloc to allocate (same thing with new).

Thank you.

Upvotes: 2

Views: 1916

Answers (2)

Scott Hunter
Scott Hunter

Reputation: 49920

Alignment is just about the location of the start of something: that its address will be a multiple of A. Where the memory manager puts those allocations, and why, is totally its business, and may be (in part) dependent on other things going on in the computer outside of your program. This means that you can't determine the "size" of a previous allocation by the location of the "next" one (while it may be next to your program, it may not be next to the memory manager); in fact, it is possible for the "next" allocation to have a smaller address (if, for example, lower memory has been freed in the interim).

Upvotes: 3

ElderBug
ElderBug

Reputation: 6145

On Windows, the malloc function is documented to return memory aligned on a 8-byte boundary for 32-bit applications, and on a 16-byte boundary for 64-bit applications. On Linux, it only said that it returns "memory that is suitably aligned for any kind of variable", but it probably is also 8 and 16.

On top of that, malloc needs to reserve additional memory to store the tracking data necessary to manage the heap. This means that when you ask for N bytes, malloc will actually use N+X bytes, with X being constant and dependent on the implementation.

Upvotes: 6

Related Questions