Stack corruption in C++

前端 未结 6 913
囚心锁ツ
囚心锁ツ 2020-12-04 22:44

In C++, in which way the stack may get corrupted. One way I guess is to overwriting the stack variables by accessing an array beyond its boundaries. Is there any other way t

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 22:59

    Violations of the One Definition Rule can lead to stack corruption. The following example looks stupid, but I've seen it a couple of times with different libraries compiled in different configurations.

    header.h

    struct MyStruct
    {
       int val;
    #ifdef LARGEMYSTRUCT
       char padding[16];
    #endif
    }
    

    file1.cpp

    #define LARGEMYSTRUCT
    #include "header.h"
    
    //Here it looks like MyStruct is 20 bytes in size    
    
    void func(MyStruct s)
    {
       memset(s.padding, 0, 16); //corrupts the stack as below file2.cpp does not have LARGEMYSTRUCT declared and declares Mystruct with 4 bytes
       return; //Will probably crash here as the return pointer has been overwritten
    }
    

    file2.cpp

    #include "header.h"
    //Here it looks like MyStruct is only 4 bytes in size.
    extern void func(MyStruct s);
    
    void caller()
    {
       MyStruct s;
       func(s); //push four bytes on to the stack
    }
    

提交回复
热议问题