Search code examples
c++cpointersdynamic-memory-allocation

C/C++ : Deallocating or deleting a block of dynamically created memory


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 ?


Solution

  • Because deallocating/freeing memory does not mean annulling or something like this.

    Freeing memory (most likely) will just mark that piece of memory as free and will not do anything else to it, until something else use it again.

    This makes the freeing memory faster.

    What you have in your code is undefined behaviour, because you're reading (using) memory, that you're not supposed to touch at all. It's "freed" and using that memory could cause anything. A crash in the best case.