如何检测 c/c++ 程序中可能/潜在的堆栈溢出问题? [英] How to detect possible / potential stack overflow problems in a c / c++ program?

查看:28
本文介绍了如何检测 c/c++ 程序中可能/潜在的堆栈溢出问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种标准方法可以查看您的应用有多少堆栈空间以及在运行期间堆栈使用的最高水印是多少?

Is there a standard way to see how much stack space your app has and what the highest watermark for stack usage is during a run?

同样在实际溢出的可怕情况下会发生什么?

Also in the dreaded case of actual overflow what happens?

它是否崩溃、触发异常或发出信号?是否有标准或在所有系统和编译器上都不同?

Does it crash, trigger an exception or signal? Is there a standard or is it different on all systems and compilers?

我专门寻找 Windows、Linux 和 Macintosh.

I'm looking specifically for Windows, Linux and Macintosh.

推荐答案

Windows 上会产生堆栈溢出异常.

On Windows a stack overflow exception will be generated.

以下 Windows 代码说明了这一点:

The following windows code illustrates this:

#include <stdio.h>
#include <windows.h>

void StackOverFlow()
{
  CONTEXT context;

  // we are interested control registers
  context.ContextFlags = CONTEXT_CONTROL;

  // get the details
  GetThreadContext(GetCurrentThread(), &context);

  // print the stack pointer
  printf("Esp: %X
", context.Esp);

  // this will eventually overflow the stack
  StackOverFlow();
}

DWORD ExceptionFilter(EXCEPTION_POINTERS *pointers, DWORD dwException)
{
  return EXCEPTION_EXECUTE_HANDLER;
}

void main()
{
  CONTEXT context;

  // we are interested control registers
  context.ContextFlags = CONTEXT_CONTROL;

  // get the details
  GetThreadContext(GetCurrentThread(), &context);

  // print the stack pointer
  printf("Esp: %X
", context.Esp);

  __try
  {
    // cause a stack overflow
    StackOverFlow();
  }
  __except(ExceptionFilter(GetExceptionInformation(), GetExceptionCode()))
  {
    printf("
****** ExceptionFilter fired ******
");
  }
}

当这个 exe 运行时,会生成以下输出:

When this exe is run the following output is generated:

Esp: 12FC4C
Esp: 12F96C
Esp: 12F68C
.....
Esp: 33D8C
Esp: 33AAC
Esp: 337CC

****** ExceptionFilter fired ******

这篇关于如何检测 c/c++ 程序中可能/潜在的堆栈溢出问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆