Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program not overflow the stack when I allocate a 11MB char array while the stack upper limit is 10MB?

I have two simple C++ programs and two questions here. I'm working in CentOS 5.2 and my dev environment is as follows:

  • g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-50)
  • "ulimit -s" output: 10240 (kbytes), that is, 10MB

Program #1:

main.cpp:

int main(int argc, char * argv[])
{
    char buf[1024*1024*11] = {0};
    return 0;
}

(Compiled with "g++ -g main.cpp")

The program allocates 1024*1024*11 bytes(that is, 11MB) on the stack but it doesn't crash. After I change the allocation size to 1024*1024*12(that is, 12MB), the program crashes. I think this should be caused by a stack overflow. But Why does the program not crash when the allocation size is 11MB, which is also greater than the 10MB-upper-limit??

Program #2:

main.cpp:

#include <iostream>

int main(int argc, char * argv[])
{
    char buf[1024*1024*11] = {0};

    std::cout << "*** separation ***" << std::endl;

    char buf2[1024*1024] = {0};

    return 0;
}

(Compiled with "g++ -g main.cpp")

This program would result in a program crash because it allocates 12MB bytes on the stack. However, according to the core dump file(see below) the crash occurs on the buf but not buf2. Shouldn't the crash happen to buf2 because we know from program #1 that the allocation of char buf[1024*1024*11] is OK thus after we allocate another 1024*1024 bytes the stack would overflow?

I think there must be some quite fundamental concepts that I didn't build a solid understanding. But what are they??

Appendix: The core-dump info generated by program #2:

Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
[New process 16433]
#0  0x08048715 in main () at main.cpp:5
5           char buf[1024*1024*11] = {0};
like image 707
yaobin Avatar asked Aug 15 '11 09:08

yaobin


1 Answers

You're wrongly assuming the stack allocations happens where they appear in your code. Anytime you have local variables whose size are known at compile time, space for those will be allocated together when the function is entered. Only dynamic sized local variables are allocated later (VLAs and alloca).

Furthermore the error happens as soon as you write to the memory, not when it's first allocated. Most likely buf is located before buf2 on the stack and the overflow thus happens in buf, not buf2.

like image 73
Per Johansson Avatar answered Oct 05 '22 06:10

Per Johansson