Access Private Members in C++

Just a proof-of-concept, not really much practical use. Also this tells us: if you REALLY want to access something, just get a pointer and start casting, lol.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Output:
 * 
 * $ g++ -w -O0 AccessPrivateField.cc 
 * $ ./a.out
 * a: 0
 * a: 9999
 * A::secretFunc called (this depends on your platform and compiler, probably won't work)
 * $
 */ 
 
#include <iostream>
#include <cstdio>
 
class A {
private:
	int a;
 
public:
	A() : a(0) {};
 
	void print();
 
private:
	void secretFunc();
};
 
void A::print() {
	std::cout << "a: " << a << std::endl;
}
 
void A::secretFunc() {
	std::cout << "A::secretFunc called" << std::endl;
}
 
int main(int argc, char **agrv) {
	A *myA = new A();
 
	myA->print();
 
	// Compilation error: cannot access private member variable
	// myA->a = 9999;
 
	// This is how you do it
	*((int *) myA) = 9999;
 
	myA->print();
 
	// try access private member function
 
	// dirty trick to convert pointer-to-member to a local address
	char buf[100];
	std::sprintf(buf, "%p", &A::print);
	unsigned long ptrAddress;
	std::sscanf(buf, "%lx", &ptrAddress);
 
	// the -0x30 offset is retreived AFTER compilation,
	// and it depends on the length of generated code for A::print
	// which renders this technique useless in practice
	void (*secretFuncPtr)(A*) = (void (*)(A*)) (ptrAddress - 0x30);
	secretFuncPtr(myA);
 
	return 0;
}

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment