Delete dynamic memory

Jul 21, 2014 at 5:22am
Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 void main()
{
clrscr();
int *ptr;
int n=20;
ptr=new int[n];
ptr[5]=7;
ptr[6]=9;
cout<<ptr[5]<<” “<<ptr[6]<<” \n”;
delete[] ptr;
cout<<ptr[5]<<” “<<ptr[6];
getch();
}


cant seem to understand…even after i use the delete function the values of ptr[5] and ptr[6] are still displayed….
Jul 21, 2014 at 5:55am
deleting memory doesn't zero it. It just tells the OS that "this memory is free and you can do whatever you want to it". Between lines 10 and 11, there are many things that could happen, and accessing this memory could very well crash your program. You were just lucky (or not depending on your philosophy) that it printed out the old values. The result is actually undefined.
Jul 21, 2014 at 7:39am
thanks
Jul 21, 2014 at 7:41am
For what it's worth: http://codepad.org/Ji7cp5oL

Btw, try converting the "garbage" value to hexadecimal. ;)
Last edited on Jul 21, 2014 at 7:43am
Topic archived. No new replies allowed.