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.
No.
"
*p = 3490should be ERROR" is defined behavior.*p = 3490is undefined behavior (UB) as the value inpis invalid after being free'd. Anything may happen.There is no should.
C does not require emitted code that checks for such mistakes.