Search code examples
cpointersmallocheap-memoryfree

about malloc() and free() in C


I have the following C-code:

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

typedef struct node
{
    int a;
}node;

int main()
{
    node * n;

    printf("\n%d\n",n->a);

    n  = (node *) malloc ( sizeof( node ));

    printf("\n%d\n",n->a);
    n->a = 6;
    printf("\n%d\n",n->a);
    free(n);
    printf("\n%d\n",n->a);
    n->a = 4;
    printf("\n%d\n",n->a);
    return 0;
}

Output obtained is :

1314172

0

6

0

4

My question is even after free(n) , why does n->a = 0 and how can we also reassign it to any value like n->a = 4 ?

Doesn't free make the memory block pointed to by n invalid ??


Solution

  • free(n);
    n->a = 4; // is not guaranteed to work, might crash on some implementations
    

    Invokes Undefined Behaviour.

    why does n->a = 0 and how can we also reassign it to any value like n->a = 4 ?

    Thats because Undefined Behaviour means anything can happen. You can't rely on that.

    P.S : Don't write such code.

    EDIT :

    As Jonathan noticed your code invokes Undefined Behavior long before you free() and then dereference n.

    node * n; //n is not initialized
    printf("\n%d\n",n->a);  //dereferencing a wild pointer invokes UB.