access violation casting to void* and back

痞子三分冷 提交于 2019-12-12 05:39:43

问题


I get an access violation reading location when I try the following. What am I doing wrong?

uint64_t hInt = 2901924954136;
void* hPoint = reinterpret_cast<void*>(hInt);

uint64_t hIntBack = *static_cast<uint64_t*>(hPoint); //get access violation 
here

回答1:


I am guessing you meant to store the address of hInt in hPoint, not the value of hInt.

uint64_t hInt = 2901924954136;
void* hPoint = reinterpret_cast<void*>(&hInt);
                                    // ^ addressof operator



回答2:


What you do is the following:

  • cast an integer to a void pointer - fine, but the pointer may point to not available memory.
  • cast the void pointer to an pointer to unsigned 64 bits integer - fine, but because of the way you got it, dereferencing it is Undefined Behaviour
  • dereference the pointer and UB gives access violation here

Casting a pointer to int to a pointer to void and back again is fine (RSahu answer), or even casting an int to a pointer and back can be (*) so this would be fine:

uint64_t hInt = 2901924954136;
void* hPoint = reinterpret_cast<void*>(hInt);

uint64_t hIntBack = static_cast<uint64_t>(hPoint);

On system where pointers use at least 64 bits (almost any current system), standard guarantees that hIntBack has same value as hInt. On old systems where pointers are less than 64 bits long, you will lose the highest order bits.


(*) In fact this is not defined by C++ standard, but is by C99. As common compilers process both languages, casting a pointer to an integer the size of which is big enough and back again will be accepted by most common compilers.



来源:https://stackoverflow.com/questions/45657427/access-violation-casting-to-void-and-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!