-1

I want to understand free() in c deallocates memory or it simply erases the data in the allocated memory by malloc.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int n;
    printf("enter the size of n:\n");
    scanf("%d", &n);
    int* A=(int*)malloc(5*sizeof(int));
    int i;
    for(i=0; i<n; i++)
    {
        printf("%d\n", &A[i]);
    }

    free(A);

    printf("\n\n-------------\n\n");

    for(i=0; i<n; i++)
    {

        printf("%d\n", &A[i]);
    }

    return 0;
}

Still after freeing A its giving the same address of A. What free() actually do?

  • 1
    What you seem to need to know about `free` in the C standard library can be found in literally *thousands* of places via google-fu. [Here is a good one](http://en.cppreference.com/w/c/memory/free), and that site is worth bookmarking. It is one of the best online references for C (and C++) you're likely to find. Regarding your program, you passed `A` by-value to `free`. it uses that value to return the memory to the heap manager for reuse. The value of `A` is not (and *cannot* be) changed. After `free` your `A` holds a *dangling pointer*, the usage of it value results in *undefined behavior*. – WhozCraig Oct 09 '16 at 09:09
  • Don't cast the result of `malloc` & friends (or `void *` in general). – too honest for this site Oct 09 '16 at 09:31

1 Answers1

0

It deallocates the memory, but since C will let you shoot yourself in the foot the pointer remains pointing to the deallocated block of memory. Using it in any way invokes undefined behavior

Tibrogargan
  • 4,508
  • 3
  • 19
  • 38