How does the compiler control protection of variables in memory? Is there a tag bit associated with private variables inside the memory? How does it work?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you mean
privatemembers of instances, then there’s no protection whatsoever at run-time. All protection takes place at compile-time and you can always get at the private members of a class if you know how they are laid out in memory. That requires knowledge of the platform and the compiler, and in some cases may even depend on compiler settings such as the optimization level.E.g., on my Linux/x86-64 w/GCC 4.6, the following program prints exactly what you expect. It is by no means portable and might print unexpected things on exotic compilers, but even those compilers will have their own specific ways to get to the private members.
(The complicated cast is there because
void*is the only type that any pointer can be cast to. Thevoid*can then be cast tochar*without invoking the strict aliasing rule. It might be possible with a singlereinterpret_castas well — in practice, I never play this kind of dirty tricks, so I’m not too familiar with how to do them in the quickest way 🙂