Home > Blockchain >  free function in C does not deallocate space if there is two or many pointers
free function in C does not deallocate space if there is two or many pointers

Time:06-27

Here I have pretty simple program which goal is to crash and show me the error. I was expecting that free function call deallocates memory then p becomes a dangling reference therefore print_pointer function crashes, but it didn't happen. Am I getting something wrong?

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

typedef struct {
    int x;
    int y;
} Point;

void print_point(Point *p) {
    printf("Point { x = %i, y = %i }", p->x, p->y);
}

int main() {
    Point *p = malloc(sizeof(Point));

    p->x = 100;
    p->y = 300;

    free(p);

    print_point(p);

    return 0;
}

For some reason I got my error when I added one new pointer to p and now its freed

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

typedef struct {
    int x;
    int y;
} Point;

void print_point(Point *p) {
    printf("Point { x = %i, y = %i }", p->x, p->y);
}

int main() {
    Point *p = malloc(sizeof(Point));

    p->x = 100;
    p->y = 300;

    Point *p2 = p;

    free(p);
    free(p2);

    print_point(p);

    return 0;
}

CodePudding user response:

Undefined behaviour does not require diagnostics or crash.

  • undefined behavior - there are no restrictions on the behavior of the program. Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar more than once in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.

The compilers are required to issue diagnostic messages (either errors or warnings) for any programs that violates any C syntax rule or semantic constraint, even if its behavior is specified as undefined or implementation-defined or if the compiler provides a language extension that allows it to accept such program. Diagnostics for undefined behavior are not otherwise required.

CodePudding user response:

Using an invalid memory location does not guarantee a crash (or segmentation fault). The behaviour is undefined.

Do not write code that invokes undefined behaviour, period.

  • Related