Search code examples
c++exceptionreinterpret-castexplicit-conversion

reinterpret_cast and STATUS_ACCESS_VIOLATION


While experimenting with C++ and the reinterpret_cast function I tried to convert a short to a string and got a STATUS_ACCESS_VIOLATION Exception.

   short s = 32767;

   short* s2 = &s;
   string* test4 = reinterpret_cast<string*>(s2);

   cout << "reinterpret_cast: " << *test4 << endl;

In my understanding, a there was a try to use a piece of memory, which is not allocated to my application's process.

How can I look out for such tryings of forbidden memory accesses? How can I reinterpret only this piece, which contains my short value?


Solution

  • You are not converting short to string; you are taking the address of a short, and then trying to access the memory at that address as if it contained a string, which it doesn't.

    Luckily, in your case, this resulted in some random piece of data being interpreted as an invalid pointer, and so you got an access violation error. If there happened to be something there that looked like a valid string structure, then all sorts of weirdness might happen.

    How can I look out for such tryings of forbidden memory accesses?

    Don't use reinterpret_cast to convert between pointers to unrelated types, and expect the reinterpreted value to point to a valid object; and don't use it at all, unless you know exactly what you're doing with it.

    How can I reinterpret only this piece, which contains my short value?

    If you want to convert the number into a string, then you could use a string stream:

    std::ostringstream stream;
    stream << s;
    std::cout << "formatted with a stringstream: " << stream.str() << std::endl;
    

    or, if you're using C++11, then there are standard functions to convert numbers to strings:

    std::string string = std::to_string(s);
    std::cout << "converted with to_string: " << string << std::endl;