Pergunta

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?

Foi útil?

Solução

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;

Outras dicas

casting does not automatically convert one data type to another. reinterpret_cast is a particularly powerful and dangerous operation that can only be used with intimate knowledge of the data types concerned. I won't go into the details here, but the long and short of it is, a pointer to short cannot be cast with reinterpret_cast into a pointer to string.

If you need to convert a short value to a string, have a look at the stringstream classes, which like other streams can consume various kinds of input (including shorts) and convert them to strings.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top