We have some C code that is throwing a STATUS_STACK_BUFFER_OVERRUN error (0xC0000409) once in a while.  I can reproduce that error using the C code below.  I'm using Visual Studio 2013 Update 4 on Windows 7, and I'm compiling with the /EHa and /GS flags. However, I have been unable to catch the error programmatically. The code never enters my __except block; instead, Visual Studio pops up a few dialog boxes informing me of the stack corruption.  I realize that once this error occurs, the state of the program is in doubt; I'm merely trying to capture the error in hopes of locating where it is occurring in our production code.  Is there a way to handle this error programmatically?
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#pragma warning(disable: 4996) // strcpy
void vulnerable(const char* str)
{
   char buffer[10];
   strcpy(buffer, str); // overrun the buffer
}
int main()
{
   __try
   {
      char large_buffer[] = "This string is longer than 10 characters.";
      vulnerable(large_buffer);
   }
   __except (GetExceptionCode() == STATUS_STACK_BUFFER_OVERRUN)
   {
      printf("error"); // never getting here
   }
}
User contributions licensed under CC BY-SA 3.0