tags:

views:

98

answers:

2

Hi,

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;
}
+11  A: 

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.

Krevan
At least on my system there is no constructor which takes a char pointer with a different char type than the underlying type. `string s = reinterpret_cast<unsigned char*>(0);` gives the error `error: invalid conversion from ‘unsigned char*’ to ‘const char*’`.
Philipp
+2  A: 

Is inStrReference NULL? Does it point to a null-terminated string? We need to see how you are calling the function.

anon