【发布时间】:2013-01-15 01:35:34
【问题描述】:
我正在尝试估计我的程序堆栈范围的跨度。我的策略是假设由于堆栈向下增长,我可以为当前堆栈帧创建一个局部变量,然后使用它的地址作为参考。
int main()
{
//Now we are in the main frame.
//Define a local variable which would be lying in the top of the stack
char a;
//Now define another variable
int b; //address should be lower assuming stack grows downwards
//Now estimate the stack size by rlimit
struct rlimit stack_size;
getrlimit(RLIMIT_STACK,&stack_size);
//A crude estimate would be stack goes from &a to &a - stack_size.rlim_cur
printf("%p \n",&a);
printf("%p \n",&b);
printf("stack spans from %u to %u",&a,&a - stack_size.rlim_cur);
return 0;
}
有趣的是,当我使用 gdb 调试 a 和 b 的值地址时,b 的地址具有比 a 更高的值。此外,堆栈指针始终保持在 .
0xbfca65f4
0xbfca660f
Stack spans from 0xbfca65f4 to 0xbbca65f4.
ebx 0xb7faeff4 -1208291340
esp 0xbffff670 0xbffff670
谁能帮我理解我哪里出错了? 提前致谢!
【问题讨论】:
-
错误的假设,除非您知道您在哪个环境中运行:stackoverflow.com/questions/664744/…。此外,我不认为 C 要求定义的顺序控制某些东西在堆栈框架中的位置。 C 只保证结构内的顺序。可能更好的方法是创建
b下一层(在被调用的函数中)。 -
我很确定您的堆栈大小计算本身是错误的,因为堆栈极不可能在不是偶数页(十六进制数以 000 结尾)的地方结束 - 但这可能是因为在您进入 main 时已经使用了一些空间。除此之外,“不能保证函数中变量之间的顺序”,我不确定我理解你的问题是什么......
标签: c memory-management stack