如何检测 c/c++ 程序中可能/潜在的堆栈溢出问题?

2021-12-21 00:00:00 memory c overflow stack 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 ******

相关文章