문제

I'm using Visual C++ 2010. I have the following function to convert a System::String^ object to char pointer (char*).

void string2charPtr(System::String^ original, char *&out) {
    int length = original->Length;
    out = new char[length+1];
    for (int i = 0; i < length; i++)
        out[i] = (char) original[i];
    out[length] = '\0';
}

Example of use:

int main(void) {
    char* cPtr;
    System::String^ str = gcnew System::String("Hello");
    string2charPtr(str, cPtr);
    delete cPtr;

    return 0;
}

Is the "delete cPtr" instruction necessary? Or if I don't call it, there will be a memory leak?

도움이 되었습니까?

해결책

Because you allocated an array, the correct statement is this:

delete [] cPtr;

And yes, without it, you have a memory leak. In this particular case, it doesn't really matter much, since the program ends immediately afterward, and the memory is then recovered by the OS.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top