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 ?
Your schema is a conceptual model or a possible implementation. But for example a multithreaded program will have one stack per thread and one single heap, which does not really fit in your simplified schema.
All what is required is that the system allows recursion, meaning that each new invocation of a functions gets a private copy of local variables. All what remains is implementation dependant.
Recent system use page allocation, and a process generally gets a set of page segments, but they are not necessarily consecutive, and you can have holes between them where any access will get a SIGSEGV (segment violation)
TL/DR: you program will more likely get a SIGSEGV signal than the address of the dynamic variable reaching the address of static one - you should find an old MS/DOS box to exhibit such behaviour...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With