mrg*_*mrg 11 c unix linux memory
程序
#include<stdio.h>
int a=10;
void main()
{
int i=0;
printf("global = %p, local = %p\n",&a,&i);
main();
}
Run Code Online (Sandbox Code Playgroud)
产量
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$
Run Code Online (Sandbox Code Playgroud)
上面的程序得到分段错误错误.因为,主要递归调用自己.以下是C程序的内存分配.
内存分配
__________________ __________________
| | | |
| 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)
Run Code Online (Sandbox Code Playgroud)
因此,我希望在图(b)中显示出主要调用的递归方式.如果它到达数据段,则发生冲突.如果它发生,则没有更多的空间来分配主函数.因此,它会出现分段错误错误.所以使用上面的程序我实验它.在该程序中,全局变量'a'的地址是"0x804a014".每次调用main时,都会声明局部变量"i".因此,我预计,在分段错误之前,i的地址几乎是'a'的地址.但是,这两个地址都非常不同.那么这是怎么回事.
为什么"a"和"i"的地址在分段错误错误时不在同一范围内.那么,如何交叉检查主要是否达到堆栈大小并溢出?
'a' 是一个全局变量,它不会在堆栈中。这将位于数据部分 - 即初始化的 bss
'i' 是一个局部变量,将存储在堆栈中。
这些是完全不同的部分,因此也存在差异。