How to free memory with something like this (Visual Studio 2008 - Win32/console):
I can include only: 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];
}
What i do wrong?
new char[]
intended to mean? It is not legal C++.new[]
s to be, say,new[6]
so that those two lines worked you immediately leak that memory by redirecting both pointers to point to string literals. The error occurs because you can onlydelete[]
something that you allocated withnew[]
and those pointers currently point to the literals. Short version, usestd:string
if you can and understand c string manipulation if you must use null terminated character buffers.