[英]System::String to char* function.. memory leak?
I'm using Visual C++ 2010. I have the following function to convert a System::String^ object to char pointer (char*). 我正在使用Visual C ++2010。我具有以下功能,可以将System :: String ^对象转换为char指针(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? 是否需要“删除cPtr”指令? 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. 在这种特殊情况下,它并没有多大关系,因为程序会在此之后立即结束,然后由OS恢复内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.