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};