如何通过监控堆栈大小来防止堆栈溢出?
许多 C/C++/Fortran 和其他程序员都会遇到“堆栈溢出”错误。 我的问题是,是否有一个工具、程序或简单的代码片段,可以让我们在程序运行时监视或检查堆栈的大小? 这可能有助于查明堆栈在何处累积并最终导致溢出。
Many C/C++/Fortran and other programmers would have come across "stack overflow" errors.
My question is, Is there a tool, a program or a simple code snippet, that allow us to monitor or check the size of the stack while the program is running? This may be helpful to pinpoint where the stack is being accumulated and eventually causing overflow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道是否有一个程序可以为您完成此操作,但您可以轻松地检查函数内部堆栈指针所在的位置(至少在 C 和 C++ 中)。 只需查看任何变量的内存位置即可。 它不会是确切的位置,但应该在几个字节之内(这适合您的目的),因为局部变量是在堆栈上定义的。 如果你想要确切的值,我相信你可以通过组装获得它。
不过,当程序崩溃时,仅查看堆栈跟踪可能会更容易。
I don't know if there is a program that'll do it for you, but you can easily check inside a function where the stack pointer is (at least in C and C++). Just look at the memory location of any variable. It won't be the exact location, but should be within a few bytes (which is fine for your purposes), since local variables are defined on the stack. If you want the exact value you can get that through assembly I believe.
It might be easier to just look at the stack trace when the program crashes, though.
看看这个问题。 接受的答案引用 Raymond Chen:
如果您确实需要这样做,那么解决方案/工具将依赖于平台。 一个简单的技巧是用已知的字节值(例如 AA)填充堆栈并监视没有该值的第一个字节的位置。 这将为您提供所使用的最大堆栈大小,而不是当前堆栈大小。
Have a look at this question. The accepted answer cites Raymond Chen:
If you definitely need to do it, then the solution/tool will be platform dependent. One easy trick is to fill the stack with a known byte value (e.g. AA) and monitor the position of the first byte that doesn't have this value. This will give you the maximum stack size used, not the current stack size.