And Is it possible to overflow into private variables?
I have no idea where to start looking into this question, so any pointers/help to it would be great!
And Is it possible to overflow into private variables?
I have no idea where to start looking into this question, so any pointers/help to it would be great!
private
variables are only made private
by the compiler. They are not located in a kind of unreachable
nor protected
memory area.
You can access them by browsing the memory if the object structure is well known (risky and absolutely not recommended, but it proves there is absolutely no protection at all.
As a proof of it (https://ideone.com/RRsOkr):
#include <iostream>
using namespace std;
class A
{
public:
A()
{
publicAttr = 4;
privateAttr = 3;
}
int publicAttr;
private:
int privateAttr;
};
int main() {
A a;
std::cout << "Public attribute value is:" << a.publicAttr << std::endl;
void* aVoid = (void*) &a; // works, but char* is recommended (see comment)
aVoid += sizeof( int );
int privateAttrValue = *((int*) aVoid);
std::cout << "Private attribute value is:" << privateAttrValue << std::endl;
return 0;
}
This program outputs the two attributes values, even if one should not be accessible!
4
3
On memory level, no protection at all.
It is purely for the developer(s) working on the code to help them avoid mistakes.
an example here:
#include <iostream>
using namespace std;
class Test
{
public:
Test() : x(10) {}
int getTest() { return x; }
private:
int x;
};
class Change
{
public:
int x;
};
int main() {
Test test; // x is 10
void* vp = &test;
Change* modify = (Change*)vp;
modify->x = 15;
cout << test.getTest(); // prints 15
return 0;
}
See it in action : http://ideone.com/MdDgUB
Access specifiers like private, public and protected don't provide any level of memory protection.