asimorio posted:
Hi all,
If I don't new up a pointer, can I delete it?
see code below:
void A::foo()
{
char* buffer;
delete buffer;
return;
}
Think of "new" as a function which returns the address of the object it
creates:
char *new();
Think of "delete" as a function which takes as an argument the address of
the object which was created:
void delete( char * );
The first line of your code defines a local variable without initialising
it. "buffer" contains white noise. It may contain the memory address
70470980, or it may contain the memory address 9327052, or it may contain
the memory address 27696368.
Now you pass this address to "delete". Bottom line is this:
You can only give "delete" an address which was returned from "new",
otherwise it's undefined behaviour.
You can only give "delete []" an address which was returned from "new
[]", otherwise it's undefined behaviour.
Of course, the exception to this is that you can safely give "delete" or
"delete []" a null pointer, and it will have no effect:
delete static_cast<char*>(0);
delete [] static_cast<char*>(0);
-Tomás