Deallocating an array

Hi all.

I an new on this forum.
I have a little problem when i try to deallocate an array.
I give the size of the array, i introduce the elements, prints them and then i try to deallocate the array.
At the end of the programm i try to print the deallocated memmory locations to see if i made correct. And is not.
When i compile you can see that just two first locations are deallocated.
Look, this is my code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<stdlib.h>

using namespace std;

int main()
{
    int n;
    cout <<"\n Give the size of the array : ";
    cin >>n;
    cout <<"\n Enter the elements : "<<endl;
    int *p = (int*)malloc(n * sizeof(int));
    for (int i=0; i<n; i++)
    {
        cout <<"\n A["<<i<<"] = ";
        cin >>*(p+i);
    }
    cout <<"\n The elements of the arrays : ";
    for (int i=0; i<n; i++)
        cout <<" "<<*(p+i);
    cout <<"\n\n";
    delete []p;
    for (int i=0; i<n; i++)
    {
          cout <<" "<<*(p+i);
    }
    cout <<"\n";
    return 0;
}


1. A malloc() call must be paired with a free() call. A usage of new must be paired with a usage of delete. Mixing allocation and deallocation functions is illegal, and produces undefined behavior.
2. Accessing (either reading or writing) deallocated memory produces undefined behavior. Assuming you fix the previous item, after line 25 is executed just once the program may do literally anything. You may see values previously held in the array, or entirely different values, or the program may make a system call that destroys all your data.
Topic archived. No new replies allowed.