Simple buffer overrun example

Question: Take a simple buffer overrun example in C/C++

Answer:

Buffer overrun, also known as buffer overflow, is to write beyond the allocated memory, typically in stack or heap memory. The following example will cause buffer overrun in stack, if command line argument is larger than 7 characters. For example, if command line argument is "1111222", it fits in buff[8] with NULL at the end. If command line argument is "11112222", buffer overflow will occur as it requires 9 bytes buffer.

// buffer overflow (buffer overrun) test program
// (How to test) C> buffover.exe 111122223333444455556666

// To disable 'strcpy' deprecation in VC++
#define _CRT_SECURE_NO_WARNINGS  

#include 
using namespace std;

void run(char* s)
{
    char buff[8];
    strcpy(buff, s);
}

int main(int argc, char *argv[])
{
    run(argv[1]);

    cout << argc;
}

To open executable with command line argument in WinDbg, add argument to "Arguments" textbox at the bottom of "Open Executable" dialog.

When running the program with long argument in WinDbg, "stack buffer overrun - code c0000409" error will be thrown.

0:000> g
(3f88.20e8): Security check failure or stack buffer overrun - code c0000409 (!!! second chance !!!)
eax=00000001 ebx=00564000 ecx=00000002 edx=000001e1 esi=00341285 edi=00341285
eip=00341bf9 esp=006ff89c ebp=006ffbc0 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000202
BuffOver!__report_gsfailure+0x19:
00341bf9 cd29            int     29h