Main function code:
PNG* allocate(size_t w, size_t h) {
PNG ret(w, h);
return &ret;
}
int main() {
PNG * image = allocate(256, 512);
delete image;
return 0;
}
Assume that appropriate PNG class is defined. My question is about allocate(); and &ret. Usually after functions are called, every created instance is cleared (only data are newly copied). In this case &ret points to the location of the newly create ret. But it seems that after function is run, ret will be deleted, and as a result, PNG * image will behave wildly.
Is this true? If so, what would be the way to fix the code?
Also, image is not created by new, so would it be sensible to use delete?
To answer your question literally, the way to fix this code is to not call delete
on any pointer that was not given to you as a result of calling new
.
delete
does two things:
In this instance the ret
object created within allocate
will be automatically destroyed when the function exits, so there is no point in trying to call its destructor. That object was also not allocated on memory provided by the runtime, so it's also meaningless to talk about releasing that memory.