dynamic memory management (arrays)


if I created an array dynamically and want to delete it. Is this correct?

1
2
3
4
5
6

int size = 5;
int *myarray = new int[size];

delete [] myarray;


I imagine that I have to iterate through each element and delete them as I go along? so the above is wrong right?

I've noticed that I can still access the value of the indexes of the array after doing the above. Is this correct?

And I mean once I've put values inside the array.
Last edited on
I imagine that I have to iterate through each element and delete them as I go along?


As designed yes, but why do int pointers? That doesn't seem very useful. Perhaps there is a good reason to do that but I can't think of one right now.

I've noticed that I can still access the value of the indexes of the array after doing the above. Is this correct?


Trying to access the data after the delete is not correct. Doing so is undefined behavior. Once the object is freed the array is returned to the heap for reuse. In a simple program it might not crash, but in a more complex program it might. The debugger is simply showing you what exists within those memory locations. delete doesn't sanitize the memory, but simply returns it to the heap for reuse. Therefore I guess you could say that seeing the old data is correct. The contents of the memory is not changed again until the heap manager gives that memory to a different requester, and then that requester puts something different there.
Topic archived. No new replies allowed.