Search code examples
c++stringpointersvoid-pointersmemory-access

Can I read any readable valid memory location via a (unsigned) char* in C++?


My search foo seems lacking today.

I would like to know if it is legal according to std C++ to inspect "any" memory location via an (unsigned(?)) char*. By any location I mean any valid address of an object or array (or inside an array) inside the program.

By way of example:

void passAnyObjectOrArrayOrSomethingElseValid(void* pObj) {
   unsigned char* pMemory = static_cast<unsigned char*>(pObj)
   MyTypeIdentifyier x = tryToFigureOutWhatThisIs(pMemory);
}

Disclaimer: This question is purely academical. I do not intend to put this into production code! By legal I mean if it's really legal according to the standard, that is if it would work on 100% of all implementations. (Not just on x86 or some common hardware.)

Sub-question: Is static_cast the right tool to get from the void* address to the char* pointer?


Solution

  • C++ assumes strict aliasing, which means that two pointers of fundamentally different type do not alias the same value.

    However, as correctly pointed out by bdonlan, the standard makes an exception for char and unsigned char pointers.

    Thus, in general this is undefined behaviour for any pointer type to read any deliberate address (which might be any type), but for the particular case of unsigned char as in the question it is allowed (ISO 14882:2003 3.10(15)).

    static_cast does compile-time type checking, so it is unlikely to always work. In such a case, you will want reinterpret_cast.