vin*_*rak 9 c linux stack-overflow compiler-construction stack
我知道堆栈大小是固定的.所以我们不能在堆栈上存储大对象,我们转向动态分配(例如malloc).此外,当存在函数调用嵌套时使用堆栈,因此我们也避免了递归函数.在运行时有没有办法确定到目前为止使用了多少堆栈内存以及剩下多少?
在这里,我假设使用x86架构的linux环境(gcc编译器).
有一个pthread API来确定堆栈的位置:
#include <pthread.h>
void PrintStackInfo (void)
{ pthread_attr_t Attributes;
void *StackAddress;
int StackSize;
// Get the pthread attributes
memset (&Attributes, 0, sizeof (Attributes));
pthread_getattr_np (pthread_self(), &Attributes);
// From the attributes, get the stack info
pthread_attr_getstack (&Attributes, &StackAddress, &StackSize);
// Done with the attributes
pthread_attr_destroy (&Attributes);
printf ("Stack top: %p\n", StackAddress);
printf ("Stack size: %u bytes\n", StackSize);
printf ("Stack bottom: %p\n", StackAddress + StackSize);
}
Run Code Online (Sandbox Code Playgroud)
在i386上,堆栈从底部开始并向顶部增长.
所以你知道你有($ ESP - StackAddress)字节可用.
在我的系统中,我有一个围绕pthread_create()的包装器,所以每个线程都在我的私有函数中启动.在该函数中,我找到如上所述的堆栈,然后找到未使用的部分,然后用一个独特的模式初始化该存储器(或"Patton",正如我的Somerville,MA出生的岳父所说的那样).
然后当我想知道已经使用了多少堆栈时,我从顶部开始并向底部搜索第一个与我的模式不匹配的值.