【发布时间】:2013-02-17 23:11:02
【问题描述】:
如何通过类似这样的方式释放内存(Visual Studio 2008 - Win32/console):
我只能包括:iostream
#include <iostream>
void data_t(char *test[])
{
test[0] = new char[];
test[1] = new char[];
test[0] = "Test1";
test[1] = "Test2";
}
int main()
{
char *test[2];
data_t(test);
cout<<test[0]<<"\n";
cout<<test[1]<<"\n";
delete[] test[0];//Debug assertion failed! - The program '[7884] Zadanie_4_sortowanie.exe: Native' has exited with code 3 (0x3).
delete[] test[1];
}
我做错了什么?
【问题讨论】:
-
new char[]是什么意思?它不是合法的 C++。 -
很遗憾,MSVS 接受了这种事情。我想知道它有什么用?
-
字符指针上的赋值运算符不会复制数据,它只是更改它只是分配指针。因此,假设您将
new[]s 固定为new[6],这样这两行就可以通过将两个指针重定向到字符串文字来立即泄漏内存。发生错误是因为您只能使用delete[]分配的东西new[]并且这些指针当前指向文字。短版,如果可以,请使用std:string,如果必须使用空终止字符缓冲区,请理解 c 字符串操作。 -
我确定数组索引是错字。你不能释放字符串文字。啊啊啊。必须... 使用.... STRCPY... 使... 教授... 感觉... 很好.. 关于成为... SO.. OLD... AS... TO ... KNOW .....C