Memory allocation for global and local variables

前端 未结 3 1133
花落未央
花落未央 2020-12-13 16:29

I have learnt that memory for global variables are allocated at program startup whereas memory for local variables are allocated whenever function call is made.

3条回答
  •  抹茶落季
    2020-12-13 16:54

    First of all: the ideone compiler is GCC.

    So, what does GCC do when you compile this?:

    void foo ()
    {
      int a[63500000];
    }
    

    gcc -S -O2 foo.c generates:

    foo:
        pushl   %ebp
        movl    %esp, %ebp
        popl    %ebp
        ret
    

    i.e. nothing is allocated on the stack, at all.

    The array is simply optimized away by GCC because it is never used.

    GCC won't do this with a global, because it is possible that a global is used in another compilation unit, and so it isn't sure that it is never used. Also: The global is not on the stack (since it is a global).

    Now, lets see what happens when you actually use the local array:

    int bar (int a, int b, int c)
    {
      int f[63500000];
      f[a] = 9;
      f[b] = 7;
      return f[c];
    }
    

    Things are very different:

    bar:
        pushl   %ebp
        movl    %esp, %ebp
        subl    $254000000, %esp
        movl    8(%ebp), %eax
        movl    $9, -254000000(%ebp,%eax,4)
        movl    12(%ebp), %eax
        movl    $7, -254000000(%ebp,%eax,4)
        movl    16(%ebp), %eax
        movl    -254000000(%ebp,%eax,4), %eax
        leave
        ret
    

    This line: subl $254000000, %esp corresponds to the size of the array. i.e. memory is allocated on the stack.

    Now, what if I tried to use the bar function in a program:

    int bar (int a, int b, int c)
    {
      int f[63500000];
      f[a] = 9;
      f[b] = 7;
      return f[c];
    }
    
    int main (void)
    {
      return bar (0, 0, 0);
    }
    

    We already saw, that the bar function allocates 250 or so megabytes on the stack. On my default GNU/Linux install, the stack size is limited to 8MB. So when the program runs, it causes a "Segmentation fault". I can increase it if I want, by executing the following in a shell:

    ulimit -s 1000000 #i.e. allow stack size to grow close to 1GB
    

    Then I can run the program, and it will indeed run.

    The reason why it fails on the ideone website is that they have limited the stack size when executing programs (and they should, otherwise malicious users could mess up their system).

提交回复
热议问题