Recently dug into the object layout and observed a loophole in C++. We know in C++ we have something called reinterpret_cast. If I need to hack the access specifier of a class not defined by us may try to use reinterpret_cast to hack it, though it is illegal but it works.
Let's see the code:
I have a class defined in a file called Demo.hpp. The class definition looks like below:
class Demo
{
private:
int x;
char ch;
public:
int x;
char ch;
public:
void print()
{
std::cout << "The value of x is: " << x << "\n";
}
};{
std::cout << "The value of x is: " << x << "\n";
}
Now I have created a class of similar structure but not exactly the same but somewhat similar to the Demo class.
class hack {
public:
int a;
};
int main()
{
Demo d;
// Through reinterpret_cast
(reinterpret_cast<hack&>(d)).a = 20;
d.print();
}
public:
int a;
};
int main()
{
Demo d;
// Through reinterpret_cast
(reinterpret_cast<hack&>(d)).a = 20;
d.print();
}
To my surprise, I am able to set the value 20 to the private variable x of the class Demo. Looks like the compiler is trying to align the object model in the way I wanted via reinterpret_cast. However, this could be disastrous also. Whatever, it is working.
Comments