Ok, let me see if I’ve got it straight. The reason I got the error on line 86 is because resize_pArray and pArray point to the same address. When I deleted pArray at line 84, the address pointed to by resize_pArray was already gone when I tried to delete it on line 86, thus causing the error message.
The memory leak on line 44 was due to the fact that I had already reserved memory on the heap for pArray on line 18. When I deleted pArray on line 42, the information in pArray was gone, but the memory for pArray itself was still reserved. Therefore, when I declared a new pArray at line 44, that was a new block of memory, which never got used.
My thinking in doing this was that I needed to declare pArray again because the array was being resized. However, since resize_pArray was expanded (+5) and copied back into pArray on line 45, that took care of resizing the array, since the “size” variable was changed to (size + 5). Therefore, I only needed to declare pArray once on line 18, and simply copy resize_pArray into pArray on line 45.
One other thing that was throwing me off. I had to delete pArray on line 42 before copying the new array back into it. At first, I couldn’t figure out why I could delete pArray without affecting resize_pArray, but I can’t do it vice versa. My assumption is that since resize_pArray has been expanded on line 38, it’s no longer the same as pArray. Therefore, when I delete pArray on line 42, it’s not the same as resize_pArray anymore, thus the latter is unaffected. The reason I can’t delete resize_pArray after line 45 is that pArray and resize_pArray now point to the exact same thing, so deleting one deletes the other, as in line 84.
EDIT: I also noticed another place where there might be a memory leak. On line 34 I created a new resize_pArray on the heap. Since it's in the
while
loop, I'm wondering if that means new memory is being reserved every time the loop iterates. Under that assumption, I inserted a line to delete resize_pArray every iteration before reserving more memory.
1 2 3 4
|
//Initialize new array on the heap
delete[] resize_pArray ;
resize_pArray = new int[ size ] ;
|
I ran the program and it works fine. I'm just wondering if my reasoning is sound about needing to delete resize_pArray before reserving new memory.