SO,
I am running into an error which I cannot figure out (unless my understanding is just incorrect).
I have the following code:
int doubleSize=size*2;
int *newArr = new int[doubleSize];
for(int i=0; i<size; i ++) {
newArr[i]=jon[i];
}
size*=2;
display(newArr);
jon=newArr;
display(jon);
delete[] newArr;
display(jon);
After the first and second calls I get exactly what I want/expect. On the third display call the 0 and 1 indices are memory addresses, the rest of the values in the indices match the previous 2 calls. What could be causing this?
I also have another follow up question, with code as I have it, will not deleting jon[] cause the 'old' jon[] to stay in memory?
Thanks!
You have undefined behavior, so anything can happen.
int *newArr = new int[size*2];
// now newArr is a pointer to a memory area
jon=newArr;
// now jon is a pointer to the same area, whatever jon pointed to before is leaked
delete[] newArr;
// now the memory area no longer exists
display(jon);
// using jon is now illegal, it has the address of a deleted memory area
Probably the right solution is:
int *newArr = new int[doubleSize]; // allocate a new area
for( int i=0; i<size; ++i ) { // fill it in
newArr[i] = jon[i];
}
delete [] jon; // get rid of the old area we don't need anymore
jon = newArr; // now jon is linked to our brand new data in a brand new area
When you delete[] newArr
, you're unallocating the memory at address newArr
. Since jon
is also pointing to that same memory (because you set jon = newArr
), the memory is being overwritten with some other values (probably in your display
function). What you need to do, is use some copy function (like memcpy
) to copy the data to a newly allocated block at jon
, not just point jon
at the same spot as newArr
.
The last display
call is trying to display jon
that is the same as newArr
- what you have just deleted! Thus the behaviour will be undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.