Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning unsigned char* to string C++

Tags:

c++

This is my sample code. Please let me know why it crashes over here.

string MyFunction::GetString(unsigned char* inStrReference)
{
    unsigned char* bufPtr = inStrReference; 

    string newstring = (char*)bufPtr;

    return newstring;
}
like image 650
boom Avatar asked Jan 22 '26 00:01

boom


1 Answers

First of all the code is identical to the much less verbose:

string MyFunction::GetString(unsigned char* inStrReference) {
   return inStrReference;
}

In fact, as it is the whole function is completely unnecessary. If var = GetString(s); is valid then var = s; is guaranteed to be valid as well and to produce the same identical result.

As for the crash, it's probably because inStrReference doesn't point to a valid memory area that contains a zero terminated string. In other words, we need more details on how this function is called to tell you what the problem is.

like image 200
Krevan Avatar answered Jan 24 '26 22:01

Krevan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!