Home > Net >  C standard conforming method to assign address of program memory to pointer
C standard conforming method to assign address of program memory to pointer

Time:08-15

How to assing internal process memory address to pointer object in C via standard conforming method?

For example, this is Undefined behavior, coz its dont defined in C Standard:

CInterpretator* pInterpretatorObj= reinterpret_cast<CInterpretator*>(0x1000FFFF);

or this, without reinterpret_cast, but with same effect:

CInterpretator* pInterpretatorObj= static_cast<CInterpretator*>(static_cast<void*>(0x1000FFFF));

Maybe using .asm file with public function who return address of object, and using this "foreign" function in C program code for get address is standard conforming or not?

But for me its very ugly. Maybe there are good methods for this.

CodePudding user response:

There is no standards-compliant way of doing this. Standard C does not have a notion of memory layout, nor of particular integers being meaningful when casted to pointers (other than those which came from casting pointers to integers).

The good news is, “undefined behavior” is undefined by the standard. Implementations are free to offer guarantees that certain types of otherwise-UB code will do something meaningful. So if you want guaranteed correctness, rather than “just happened to work”, you won’t get that from the Standard but you may get it from your compiler documentation.

For literally all C compilers I know of, using reinterpret_cast as you’ve done here will do what you expect it to do.

  • Related