Home > Enterprise >  Why does my buffer have more memory allocated on the stack than I asked for?
Why does my buffer have more memory allocated on the stack than I asked for?

Time:11-07

Here's my source code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500

int main(int argc, char** argv)
{
        if (argc != 2)
                exit(1);
        char str[MAX];
        strcpy(str, argv[1]);
        return 0;
}

I disassembled main using gdb and got the following result:

Dump of assembler code for function main:
   0x0000000000001145 < 0>:     push   %rbp
   0x0000000000001146 < 1>:     mov    %rsp,%rbp
   0x0000000000001149 < 4>:     sub    $0x210,%rsp
   .
   .
   .
End of assembler dump.

Here the notable thing is:

0x0000000000001149 < 4>: sub $0x210,%rsp

and my question is-
Why is there $0x210 (528 bytes), when it should be $0x1f4 (500 bytes) as I asked for?

CodePudding user response:

I am guessing you are using gcc and compiling without optimizations, like this (godbolt).

There are a couple things going on here:

First, when compiling without optimizations, the compiler tries to ensure that every local variable has an address in memory, so that it can easily be inspected or modified by a debugger. This includes function parameters, which on x86-64 are otherwise passed in registers. So the compiler needs to allocate additional stack space where the argc and argv parameters can be "spilled". You can see the spilling at lines 5 and 6 of the assembly:

        movl               
  • Related