1

I decided to ask the question on this forum because I can not figure out why struct allocation makes the additional 16 bytes space on local function stack(third line at the second snippet).

Here is the c++ simple code and its corresponding assembly version

struct product {
  int weight;
} ;

void test() {
product* p;

p=new product();
p->weight=1;
}
push    rbp
mov     rbp, rsp
sub     rsp, 16
mov     edi, 4
call    operator new(unsigned long)
mov     DWORD PTR [rax], 0
mov     QWORD PTR [rbp-8], rax
mov     rax, QWORD PTR [rbp-8]
mov     DWORD PTR [rax], 1
nop
leave
ret

1 Answer 1

1

In the future additional information like what architecture and OS is this for would help because the answer does make a difference. (e.g. a long in x86_64 Windows is 32bits, where as Linux it is 64bits).

However lets assume this is x86_64 based on the registers used and turns out here the size of a long doesn't matter.

The short answer is that it's not the struct. It's the pointer to the struct. That 'p' has to go someplace.

Additionally things returned by new in MOST x86_64 operating systems are 16 byte aligned and so is the stack for performance reasons. So that's where the extra 8 bytes is likely coming from. Could also be space for a stack cookie that's being hidden from your debugger output depending on where you got that assembly output from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.