2

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!

Impulse
  • 155
  • 11

3 Answers3

3

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
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • I just want to add that the compiler is allowed to put private and public member blocks in whatever order it chooses so the next spot after `aVoid` might be outside the class – NathanOliver Sep 19 '15 at 13:46
  • Aside: doing arithmetic with `void*` is not permitted by the standard; use `char*` for that (also, `int*` would probably be simpler here). See http://stackoverflow.com/a/3524270/1084944 –  Sep 19 '15 at 14:24
  • @Hurkyl: Interesting, did not know. Thanks. – jpo38 Sep 19 '15 at 17:07
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

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

Access specifiers like private, public and protected don't provide any level of memory protection.

Steephen
  • 14,645
  • 7
  • 40
  • 47