B
B. Penn
Hi,
I was testing pointers and found that I could still dereference a
pointer and access the value/variable it pointed to after deleting it,
which confused me for "the variable it pointed to is deleted and it
now points to nowhere". Did I do anything wrong? I checked a couple
of references but couldn't explain it. Could anyone kindly clear it
for me please?
Here is my code, which compiled with both GNU C++ and Visual Studio
..Net:
-------------------------------
int *p = new int;
*p = 5;
cout<<p<<' '<<*p<<endl;
delete p; // DELETE
cout<<p<<' '<<*p<<endl; // could be dereferenced
*p = 10; // could access the variable
cout<<p<<' '<<*p<<endl;
I was testing pointers and found that I could still dereference a
pointer and access the value/variable it pointed to after deleting it,
which confused me for "the variable it pointed to is deleted and it
now points to nowhere". Did I do anything wrong? I checked a couple
of references but couldn't explain it. Could anyone kindly clear it
for me please?
Here is my code, which compiled with both GNU C++ and Visual Studio
..Net:
-------------------------------
int *p = new int;
*p = 5;
cout<<p<<' '<<*p<<endl;
delete p; // DELETE
cout<<p<<' '<<*p<<endl; // could be dereferenced
*p = 10; // could access the variable
cout<<p<<' '<<*p<<endl;