Why does an 8-byte array (C) in 64-bit Ubuntu take 16 bytes?

4

I've recently been (relearning) lower level CS material and I've been exploring buffer overflows. I created a basic C program that has an 8-byte array char buffer[8];. I then used GDB to explore and disassemble the program and step through its execution. I'm on a 64-bit version of Ubuntu, and I noticed that my 8-byte char array is actually represented in 16 bytes in memory - the high order bits all just being 0.

E.g. Instead of 0xDEADBEEF 0x12345678 as I might expect to represent the 8 byte array, it's actually something like 0x00000000 0xDEADBEEF 0x00000000 0x12345678.

I did some googling and was able to get GCC to compile my program as a 32-bit program (using -m32 flag) - which resulted in the expected 8 bytes as normal.

I'm just looking for an unambiguous explanation as to why the 8-byte character array is represented in 16 bytes on a 64-bit system. Is it because the minimum word size / addressable unit is 16 bytes (64 bits) and GDB is simply printing based on an 8-byte word size?

Hopefully this is clear, but let me know if clarification is needed.

c
64-bit
x86-64
32bit-64bit
sizeof
asked on Stack Overflow Jan 22, 2013 by DJSunny • edited Oct 29, 2020 by phuclv

1 Answer

6

64bit systems are geared toward aligning all memory to 16 byte boundries (16 byte stack alignment is part of the System-V ABI), for stack allocations, there are two parts to this, firstly, the stack itself needs to be aligned, secondly any allocations then try to preserve that alignment.

This explains the first part as to why the 8 byte array becomes 16 bytes on the stack, as to why it gets split into two 8byte qwords, this is a little more difficult to tell, as you haven't provided any code (assembly or C) as to the use of this buffer. And trying to replicated this using mingw64 provides the 16 byte alignment, but not the funny layout you are seeing.

Of course, the other possibility stemming from the lack of ASM is that GDB is displaying 2xQWORD's even though its in fact 2xDWORD's (in other words, try using p/x (char[8]) to dump the contents...).

answered on Stack Overflow Jan 22, 2013 by Necrolis

User contributions licensed under CC BY-SA 3.0