2

I am trying to convert a managed byte array to std::string in my C++/CLI wrapper; however, I am seeing some corrupt memory in the heap later on. Just wanted to check if I am doing the conversion right. Below is my method is CLI:

string ByteArrayToStr(array<Byte>^ byteArray)
{
    int size = byteArray.Length;
    IntPtr pnt = Marshal::AllocHGlobal(size + 1);
    char* chararray = (char*)pnt.ToPointer();
    try
    {
        Marshal::Copy(byteArray, 0, pnt, size);
        *(chararray + size) = 0;
        return string(chararray);
    }
    finally
    {
        Marshal::FreeHGlobal(pnt);
    }
}

Does anything seem wrong in above code?

3
  • I don't see any problems in that code. I would change the second line in the try block to use chararray[site], but that would be just more readable, it wouldn't change what the code does. Commented Mar 14, 2012 at 0:42
  • You don't typically need a lot of help from C++/CLI code to corrupt the heap. This isn't it. Commented Mar 14, 2012 at 0:43
  • Thank you for the validation. There must be some bug my code elsewhere; I shall take a look. Thank you, Raj. Commented Mar 14, 2012 at 3:29

1 Answer 1

3

You are doing an unnecessary explicit copy and playing with a manual memory allocation.

You could just pass the raw pinned pointer to std::string constructor:

string ByteArrayToStr(array<Byte>^ byteArray)
{
    pin_ptr<unsigned char> temp = &byteArray[0];
    return string(reinterpret_cast<char*>(temp), byteArray->Length);
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's definitely much simpler. I believe the 'str' in the second line was a typo though. Thank you.
BTW, pin_ptr goes out of scope when the function returns. Does std::string constructor do the copying of managed data pointed to by 'temp' into unmanaged data so that the returned string can be used later?
@user392005 Yes, std::string copies the data in its own internal buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.