I can assign value to pointer after freeing it from manually allocated memory

97 Views Asked by At

I am not sure why I am getting value 3490 evven if the author says *p = 3490 should be ERROR since we are doing it after free(). Any ideas?

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

int main()
{

    // Allocate space for a single int (sizeof(int) bytes-worth):

    int *p = malloc(sizeof(int));

    *p = 12; // Store something there

    printf("%d\n", *p); // Print it: 12

    free(p); // All done with that memory

    *p = 3490;          // ERROR: undefined behavior! Use after free()!
    printf("%d\n", *p); // Print it: 3490
}

I tried compiling and value still shows up. I do not see any undefined behavior.

3

There are 3 best solutions below

0
chux - Reinstate Monica On

*p = 3490 should be ERROR ...

No.
"*p = 3490 should be ERROR" is defined behavior.
*p = 3490 is undefined behavior (UB) as the value in p is invalid after being free'd. Anything may happen.
There is no should.

C does not require emitted code that checks for such mistakes.

2
Eric Postpischil On

if the author says *p = 3490 should be ERROR

The author does not say that. The text says “ERROR”, not “should be ERROR”.

The author is not saying the compiler should report an error. The author is not saying the program should report an error. The author is not saying the operating system should report an error.

The author is saying the person who wrote the code made an error.

Then it says “undefined behavior”. That means the behavior of the program is not defined.

There is no definition, no specification, in the C standard for what the program is required to do. There is no specification that it will report an error. There is no specification that it will not report an error. There is no specification that it will print “3490”. There is no specification that it will not print “3490”.

The lesson is you must learn not to make such errors, and the C programming language will not help you find them.

1
ldn On
  • After using free() on a pointer, the memory it points to is marked as free, but the pointer itself doesn't change.
  • It still points to the same location, which may now contain different data, as it can be overwritten.
  • To avoid using a freed pointer, set it to NULL after freeing it.