Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

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.

like image 334
Mathology Avatar asked Dec 06 '25 07:12

Mathology


2 Answers

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.

like image 85
Eric Postpischil Avatar answered Dec 08 '25 21:12

Eric Postpischil


*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.

like image 44
2 revschux - Reinstate Monica Avatar answered Dec 08 '25 20:12

2 revschux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!