0
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    struct node *pre;
    struct node *next;
    int data;
}NODE; //struct declaration

int main(){

    NODE *new_node=(NODE*)malloc(sizeof(NODE)); //memory allocation

    printf("\nnew_node addr: %d\n",new_node);

    free(new_node); //deallocation

    printf("new_node addr: %d\n",new_node);


}

Result:

new_node addr: 2097152
new_node addr: 2097152
Program ended with exit code: 0

Why the results are same?
I deallocate the new_node's memory. But new_node has address.
Why??

Kate
  • 23
  • 1
  • 7
  • For the same reason `int a = 5; printf("a=%d\n", a); free(new_node); printf("a=%d\n", a);` will print `a=5` twice. – mah Mar 20 '15 at 16:54
  • Apparently you think I'm not actually answering you -- but I am. Just as in my silly code, there's no reason for the value of `a` to change, there's no reason for the value of `new_node` to change. – mah Mar 20 '15 at 17:03

2 Answers2

8

Calling free deallocates the memory that the pointer points to, but it does not change the memory address stored in that pointer. After calling free, you should not attempt to use the memory. To be safe, you can manually set the pointer to NULL:

free(new_node);
new_node = NULL;

You sold your house and it got demolished, but you still have the address written on a piece of paper.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
7

free() doesn't change the value of the pointer passed to it. It just releases the memory allocated at that pointer. In other words, the pointer still points to the same place, there just is no longer guaranteed to be anything there.

If you need to detect that a pointer has been freed, assign it to NULL:

new_node = NULL;

You could even write a little macro to always do this for you (though I wouldn't recommend it as it can make your code more difficult to read):

#define FREE_SET_NULL(pointer) free(pointer);pointer=NULL;
aruisdante
  • 8,875
  • 2
  • 30
  • 37
  • Then what can I do to delete the new_node's address? – Kate Mar 20 '15 at 16:56
  • 1
    @user4694907 deleting the address doesn't mean anything. What you can do is set the address to something you can easily identify as not pointing anywhere. For example, NULL! – juanchopanza Mar 20 '15 at 16:57
  • Assign the pointer to NULL if you like, but that doesn't really accomplish anything. Once you `free()` the memory, accessing it may cause anything to happen--or nothing. But it's none of your business, because it doesn't belong to you anymore. – Lee Daniel Crocker Mar 20 '15 at 16:58
  • Wow great good good!!!! Thanks – Kate Mar 20 '15 at 16:59