Program
#include<stdio.h>
int a=10;
void main()
{
int i=0;
printf("global = %p, local = %p\n",&a,&i);
main();
}
Output
mohanraj@ltsp63:~/Advanced_Unix/Chapter7$ ./a.out
global = 0x804a014, local = 0xbfff983c
global = 0x804a014, local = 0xbfff980c
.
.
.
global = 0x804a014, local = 0xbf7fac9c
global = 0x804a014, local = 0xbf7fac6c
global = 0x804a014, local = 0xbf7fac3c
Segmentation fault (core dumped)
mohanraj@ltsp63:~/Advanced_Unix/Chapter7$
The above program gets segmentation fault Error. Because, the main gets call itself recursively. The following is the memory allocation to a C program.
memory allocation
__________________ __________________
| | | |
| stack | | Main |
| ↓ | |----------------|
------------------ | Main |
| | |----------------|
| <Un Allocated| | Main |
| space> | |----------------|
------------------ | Main |
| | |----------------|
| ↑ | | Main |
| Heap | |----------------|
| | | Main |
| | |----------------|
__________________ |////////////////| ---> Collision occurs. So, Segmentation fault Occurs.
| | |________________|
| data | | data |
__________________ |________________|
| text | | text |
__________________ |________________|
Figure(a) Figure(b)
So, I expect which is showed like in figure(b), the main call recursively. If it reaches the data segment, the collision occurs. If it occurs, there is no more space to allocate for main function. So, it gets segmentation fault error. So using the above program I experiment it. On that program, the address of global variable 'a' is "0x804a014". Each time main is called, the local variable "i" gets declared. So, I expect, before the segmentation fault, the address of i is nearly to address of 'a'. But, both the address are very different. So what's here going on.
Why the address of 'a' and 'i' is not in the same range at the time of segmentation fault error. So, how to cross check whether the main reaches the stack size and gets overflowed ?
/proc/pid/maps- there are other things in there, such as libraries. Plus there's an actual limit on the stack size (ulimit) - Peteshulimit, which is (typically) 8MB. Even on a 32bit system, you will never get the stack to overlap with the data segment in that case; even if there wasn't a bunch of libraries between them. I'm trying to guide you to understanding that an address map of a real process is different from the simple one you've shown. - Petesh