is it OK to delete a char* before new was called for it?
example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void read(char*& text)
{
delete text;
text = newchar[255];
text = "hello";
}
int main()
{
char* text;
read(text);
printf("%s", text);
delete text;
}
the reason i write it this way 'cus read() wants to be sure it is given a char[255] pointer, not a char[16] and not an unallocated char*. Deleting "text" and making "text = new char[255]" seems a very easy workaround.
Wouldn't there be any problems with it?
void read(char*& text)
{
delete [] text; // deleting arrays needs delete [] not just delete
text = newchar[255];
strcpy(text, "hello"); // as was pointed out by coder777
}
int main()
{
char* text = NULL; // init to NULL (not it's safe to call delete on it!)
read(text);
//printf("%s", text); huh - C code?
cout << test << "\n"; // we are using C++ here!?
delete [] text; // still need the []
}
It is a good habit to initialize all variables. And esp. here -- init-ing text to NULL makes it safe to call delete [] in it.