-
weird pointer issue
Hey everyone,
I haven't programmed in quite some time and was trying to get back into it. So I wrote a small tester program that's already giving me an issue:
Code:
int* arr = new int[10];
for (int i = 0; i < 10; ++i)
arr[i] = i * 2;
for (int i = 0; i < 10; ++i)
cout << arr[i] << endl;
arr++;
delete [] arr;
When I debug this, arr has 4 added to it (correct) and *arr equals the next element up (correct), but I'm getting an assertion error. Any insight into this crazy stuff?
Thanks a lot!
-
My forte is C, but my guess would be that you have to use delete on the original pointer value, but yours is being modified.
-
wow
Fantastic observation, and you have just taught me something new. Thanks a lot! Random question, is it possible to call delete on a modified pointer like this?
-
If you could, you wouldn't be getting an assertion error ;)
-
Chaplin> Random question, is it possible to call delete on a modified pointer like this?
A better question is "how does delete/free() know how much memory to free when being called with a pointer?"
Think about it.
...A pretty common implementation is to also allocate some space just before the pointer, and there store the size of memory being allocated. That way, when delete or free() is being called they just move back and find the size of the chunk to free.
And to furthermore answer your question; no, it isn't.
-
And remember by delete[] you are deleting the array that pointer is pointing to, not the pointer itself, pointer remains in the stack until the end of its scope (if its automatic like your case).