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;
}

The result obtained:

1314172

0

6

0

4

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

Is the block of memory pointed to by n invalid?

+3
source share
7 answers
free(n);
n->a = 4; // is not guaranteed to work, might crash on some implementations

Invokes Undefined Behavior.

why n-> a = 0 and how can we reassign it to any value, for example n-> a = 4?

Thats because Undefined Behavior means that anything can happen. You cannot rely on it.

PS: Do not write such a code.

EDIT :

Jonathan Undefined Behavior free(), n.

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

, , , , , . , , , .

+13

, . . / , , , .

, , .

+4

, undefined. , . - .

, free , . , . , .

, , , , " ". C !:)

+4

. , ; , . , ( , , )

; ; (tm)

+1

, MMU (, x86), - . MMU , , , , , , - .

, , . MMU, MMU , , ( ).

, malloc() -, , , free(), , , .

, , mmap(), .

0

Most of the OS allocates a certain minimum space, which will be equal to or more than the space requested by you. As soon as you call for free, this space will not return to the OS, but will remain with you for reuse in the future. Therefore, you can leave with something like what you wrote above.

But, strictly speaking, this is classified as "Undefined" behavior. But you can leave with him most of the time. Just don't make habits;)

0
source

Source: https://habr.com/ru/post/1765671/


All Articles