Possible Duplicate:
C++ delete - It deletes my objects but I can still access the data?
I am trying to deallocate a block of dynamically created memory in C/C++.
But both the standard methods I used (malloc/free and new/delete) seems to be dysfunctional.
The o/p of both the codes given below is similar.
Here is code using malloc/free :
#include<stdio.h>
#include<stdlib.h>
int main(){
int * arr;
arr = (int *)malloc(10*sizeof(int)); // allocating memory
int i;
for(i=0;i<10;i++)
arr[i] = i;
for(i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
free(arr); // deallocating
for(i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
}
Here is code using new/delete[] :
#include<stdio.h>
#include<stdlib.h>
int main(){
int * arr;
arr = new int[10]; // allocating memory
for(int i=0;i<10;i++)
arr[i] = i;
for(int i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
delete[] arr; // deallocating
for(int i=0;i<10;i++)
printf("%d ",arr[i]);
printf("\n");
}
But, even after deallocating the memory, none of them are giving any errors.
The o/p in both the cases is same :
0 1 2 3 4 5 6 7 8 9
0 0 2 3 4 5 6 7 8 9
So, what is the correct method of deallocating memory in C/C++ ? Also, why is the array is getting printed even after deallocating the memory ?