0

I made a dynamic array (example):

int *a;
a = new int[3];
a[0] = 10; a[1] = 20; a[2] = 30;

Than I create a vector which stores pointers:

vector<int*> pa;
pa.push_back(&a[0]);

After I deleted (freed) the memory with "delete[] a;", I can still access to the element, that I push_backed. (cout << *pa[0]; output: 10)

Why is this happen? When I "delete[] a", it only deletes the pointer to the elements, but the elements are still accessable?

Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • 1
    Don't miss out on this wonderful answer about memory and undefined behavior. http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794. – R Sahu Mar 01 '17 at 19:37

1 Answers1

1

Your statement about how delete[] works is backwards. It deletes the elements but not the pointer. Continuing to use the pointer after its contents have been deleted, as you're doing, is undefined behavior. This means that literally anything is allowed to happen if you do it, so you shouldn't do it. It's by pure luck that you can still access the elements now, and bad things will happen in the future if you do it.