Deleting pointer

Why do I get a random value here I deleted p. Also, why is compiler allowing p[][]. I get it that p is not set to null but doesnt deleting a pointer mean that part of the memory is deallocated? And If I dont assign p = nullptr; and somehow
when I declare some object(lets say int for now), the compiler assigns it to p[0][0] and now I can access that value which is not good. So what does delete actually do ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  int main(){
  int **p;
  int** g;
  p = new int*[4];
  p[0] = new int[3];
  p[1] = new int[3];
  p[2] = new int[3];
  p[3] = new int[3];

  int count = 0;
  for(int i = 0; i < 4; ++i) {
    p[i][0] = ++count; p[i][1] = ++count; p[i][2] = ++count;
  }
  int** t = &p[0];
  int** x = &p[1];
  int** y = &p[2];
  delete p;
  cout << x[0][1] <<endl;
  cout << p[0][0] <<endl; //Why do I get a random value here I deleted p. 
  cout << *p << endl;

}
Hi,

http://en.cppreference.com/w/cpp/memory/new/operator_delete

Why do I get a random value here I deleted p.


What were you expecting? Consider this: Someone has taken your house keys, and replaced them with some other random keys; should you expect those keys to provide a sensible outcome when used for your house?

Also, why is compiler allowing p[][].


Pointers, arrays, and pointer arithmetic are very closely related. Given int** p; then initialising p means one can do pointer arithmetic or use subscripts on a 2d array.

Just because delete de-allocates memory, it doesn't mean that access to it will produce a compile error or warning, it just means that it is invalid.
its generally considered a good plan to do this

delete [] p; p = null;

if p is going to "survive" after the deletion as an accessible entity. If p vanishes (the delete is in the destructor of a class, for example, after which p no longer exists) you can use your common sense, a sackful of pointless assignments is visual clutter and a performance hit in some cases (imagine assigning null to 10 pointers or so in a destructor ... except the user had an array of 5 million objects of your class type to destroy!).

What you have is logically the same problem as this:

int *p;
p[1962] = 11; //p is uninitialized and could be pointing to ANYTHING -- this is probably going to crash and stuff. You can DO it, the compiler allows it with just a warn, but its not correct.

Topic archived. No new replies allowed.