0
int main() 
{   
    int *p,*q;  
    p=(int *)malloc(sizeof(int));   
    *p=5;   
    free(p);
} 

When I examine the memory address allocated to p after the execution of the free(p) statement, I observe that the memory content is 0. Is this the right behavior because I have read that free does not initialize the memory to 0?

jmrk
  • 34,271
  • 7
  • 59
  • 74
  • 1
    It does not guarantee to do so, but is allowed to. Some dynamic memory managers use the content of unallocated memory to store administration data on available memory. Being able to access it seems to be a case of luck, it could easily cause a segfault. – Yunnosch Aug 15 '17 at 16:34
  • No need to cast the return value of malloc as its return type is void*. – MCG Aug 15 '17 at 16:40
  • This code has undefined behavior. – MCG Aug 15 '17 at 16:54
  • 1
    @MCG Aside from maybe missing `#include <...>`, what [UB](https://stackoverflow.com/questions/45697247/free-initialising-memory-to-0#comment78353721_45697247) are you suggesting? – chux - Reinstate Monica Aug 15 '17 at 16:56
  • @chux It's UB in a hosted environment. – Ian Abbott Aug 15 '17 at 17:03

1 Answers1

3

The content of *p after free(p) returns is undefined. It may be 0, 42 or anything else.

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

int main(void) {
    int *p, *x;

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

    // the following will print "0x7fd0cac00350: 5" or similar
    printf("%p: ", p);
    printf("%d\n", *p);

    free(p);

    printf("%p\n", p); // won't change from before
    printf("%d\n", *p); // UNDEFINED BEHAVIOR
}
Jeremy
  • 566
  • 1
  • 6
  • 25