估计线程堆栈大小
我试图猜测在每个线程的基础上分配多少堆栈。 发现提示建议程序应在内存中写入已知模式(例如:0xEF
),以获取堆栈的上限/下限。
有人可以提供快速的 C 程序来做到这一点吗?这真的是要走的路吗? 还有其他建议吗?
感谢您协助解决这个疑问。
Am trying to guess-timate how much stack to allocate on per thread basis.
Found hints that suggest program should scribble a known pattern (ex: 0xEF
) in memory, to get upper/lower bounds of stack.
Can someone provide quick C program to do so? Is this truly the way to go?
Any other suggestions?
Thank you for assisting with this doubt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您完全控制您的程序(代码),那么尝试找到大小是无意义的,因为您将是在您创建时告诉操作系统分配特定数量的堆栈大小的人使用
CreateThread
或pthread_create
的线程。但是,如果您不这样做,根据您的操作系统,您可以调用pthread_attr_getstack
(在 unix 上)或VirtualQuery
(在 Windows 上),分配基于堆栈的变量,并计算堆栈基地址和变量位置之间的距离。If you have complete control of your program( code ), it's a nonsense trying to find the size because you would be the one who's telling the OS to allocate the specific amount of stack size when you're creating a thread using
CreateThread
orpthread_create
. However, if you don't, depending on your OS, you can either callpthread_attr_getstack
(on unix) orVirtualQuery
(on Windows), allocate a stack-based variable, and calculate the distance between the base address of the stack and the position of your variable.估计堆栈使用情况的另一种方法是读取每个函数中的堆栈指针值并更新最小和最大堆栈指针变量。在程序结束时,两个值之间的差异将为您提供估计值。
为了读取堆栈指针的值,您可以:
mov r/eax, r/esp
+ret
代码:
输出:
我也知道某些编译器支持挂钩函数入口(并且可能退出),这可以简化任务,因为这样您就不需要将
UpdateStackUsage();
插入到所有/许多函数中。 此处对此进行了讨论。An alternative way to get an estimate of the stack usage is to read the stack pointer value in every function and update the minimum and maximum stack pointer variables. At the end of the program the difference between the two values will give you the estimate.
In order to read the value of the stack pointer you can:
mov r/eax, r/esp
+ret
for the x86 CPU)Code:
Output:
I also know that some compilers support hooking function entry (and probably exit), which can simplify the task because with that you won't need to insert
UpdateStackUsage();
into all/many of your functions. That's been discussed here.