Reputation: 35
Say I have this:
char* data = new char[3];
char* tmp = data;
data = new char[3];
after that should I call delete for both pointers like so:
delete[] data;
delete[] tmp;
or is it just for data:
delete[] data;
I tried the first way but it gave me a heap error, the second way didn't cause me any problems, but then what happens to the memory tmp is pointing to, would there be a memory leak there?.
Upvotes: 0
Views: 58
Reputation: 63777
It is important to understand that the delete
operator releases any memory that was allocated by a previous new
. So depending upon, the occurrence of new, the call to delete for the same allocated memory should match.
In your case, there are two invocation to new
, new char[3]
assigned to data
which was further assigned to tmp
. At this point, both tmp
and data
refers (points) to the same memory location on the heap. A second invocation of new
, new char[3]
further allocates memory equivalent to 3 character storage and assigns it to data
. Thus it would make sense, to call delete
twice on both the allocated blocks, refereed individually by tmp
and data
.
Upvotes: 2