且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-10 14:06:40

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

On Windows a stack overflow exception will be generated.

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

The following windows code illustrates this:

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

void ***()
{
  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
  ***();
}

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
    ***();
  }
  __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 ******