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?
Since “Test1” and “Test2” are used by your program at runtime (they are printed by cout), the compiler has to save them somewhere. It does this by putting them both into your executable.
Since they are both in your executable already, there is no reason to allocate any new memory.
So you can remove the first two lines in data_t.
If you do this you will get a compiler error, though this error should have already been there, which will complain that you are trying to assign a string literal (“Test1”, “Test2”) to a non const array.
The problem here is that strings saved by the compiler into the executable are NOT to be modified. You are only printing them, but data_t doesn’t know that. To fix the problem you should use
const char *instead ofchar *If you intend to modify these strings, you’ll need to allocate new memory and copy the strings into it.