How to detect possible / potential stack overflow problems in a c / c++ program?

前端 未结 9 1851
滥情空心
滥情空心 2020-12-04 21:55

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 o

9条回答
  •  無奈伤痛
    2020-12-04 22:24

    On Windows a stack overflow exception will be generated.

    The following windows code illustrates this:

    #include 
    #include 
    
    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\n", 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\n", context.Esp);
    
      __try
      {
        // cause a stack overflow
        StackOverFlow();
      }
      __except(ExceptionFilter(GetExceptionInformation(), GetExceptionCode()))
      {
        printf("\n****** ExceptionFilter fired ******\n");
      }
    }
    

    When this exe is run the following output is generated:

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

提交回复
热议问题