如何通过监控堆栈大小来防止堆栈溢出?

发布于 2024-07-22 08:14:26 字数 117 浏览 2 评论 0原文

许多 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

皇甫轩 2024-07-29 08:14:26

我不知道是否有一个程序可以为您完成此操作,但您可以轻松地检查函数内部堆栈指针所在的位置(至少在 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.

过气美图社 2024-07-29 08:14:26

看看这个问题。 接受的答案引用 Raymond Chen:

If you have to ask, you're probably doing something wrong.

如果您确实需要这样做,那么解决方案/工具将依赖于平台。 一个简单的技巧是用已知的字节值(例如 AA)填充堆栈并监视没有该值的第一个字节的位置。 这将为您提供所使用的最大堆栈大小,而不是当前堆栈大小。

Have a look at this question. The accepted answer cites Raymond Chen:

If you have to ask, you're probably doing something wrong.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文