what if delete before new?

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 = new char[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?
Last edited on
Wouldn't there be any problems with it?
The problem in your case is that you pass an uninitialized pointer which [likely] leads to a crash.

On line 5 you replace the newly allocated memory pointer with a static pointer to a string with the result that delete will crash. Use strcpy instead.
thx mate:)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void read(char*& text)
{
   delete [] text; // deleting arrays needs delete [] not just delete
   text = new char[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.

Andy
Last edited on
Topic archived. No new replies allowed.