How to Hack C++ Code?

Artiom Baloian
3 min readNov 25, 2018

Introduction

Have you ever thought how to hack the C++ code? Let’s go and see what kind of hack it is.

In 1979, Bjarne Stroustrup began working on the “C with Classes” programming language at AT&T Bell Labs. In 1983, “C with Classes” was renamed to “C++” (++ being the increment operator in C).

C++ inherited most of C’s syntax and Simula’s features but C++ introduces Object- Oriented Programming (OOP) features to C.
In general, OOP provides abstraction, encapsulation, inheritance, and polymorphism. It is also correct to say that C++ offers classes, which provide the above mentioned four common features of OOP.
In this article I am going to briefly explain what encapsulation is and demonstrate how we can hack it.

Encapsulation in C++

There is no unique definition of encapsulation, it is an OOP concept/mechanism that binds together data (data members) in order to prevent access to the data if it is defined as private. It is a kind of concept/mechanism of data hiding. In C++ to have access to hidden data is provided through the functions of the class (member functions).
For example,

class MyClass {
private:
int data;
public:
MyClass(int value): data(value) {}
~MyClass() {}
void print() { std::cout << a << “\n”; }
};

So that begs the question, is (data member data) really private? can I have access to data outside of class’ interface, like this my_object.data?
Answer: In theory you cannot, because it is private, but in practice you can, it is because C++ inherits some really cool features from C, like providing access to variable’s value through memory address and change value.

Let’s Hack It

So, how is it possible to change the value of a private data member without member function? Here is how.

MyClass my_obj(5);
my_obj.print(); // Here it should print 5
int* obj_ptr = (int*)(&my_obj);
(*obj_ptr)++;
my_obj.print(); // Here it should print 6

How does it work ? To answer this question, let’s go to memory level and see how an object is stored on memory. When you declare an object
MyClass my_obj(5);this is (see Pic 1.) how it will look like in memory (assuming that system is 64 bit and int is 4 byte).

Pic 1.

So, when program calls int* obj_ptr = (int*)(&my_obj); line, then the value of obj_ptr will be 0x7ffd2d0caf6c and we know that it is possible to change the value of a variable through a pointer in C/C++.

Conclusion

The current hack/trick was tested on Ubuntu 18.04 (4.15.0–39-generic, x86_64) and source code was compiled by g++ compiler (version 7.3.0).
So, does encapsulation work or make sense for C++ ?

Happy Hacking!

If you have learned something new, please share and recommend this to allow others to learn too!

--

--