Search code examples
csegmentation-faultdangling-pointer

Why my dangling pointer doesn't cause a segmentation fault?


My code:

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

int main(void) {
    int *p = (int *)malloc(sizeof(int));
    free(p);
    *p = 42;
    return 0;
}

I created a pointer, then I pointed it to allocated space and finally I had assigned 42 to it. In my opinion it should not work, it should cause a segmentation fault, but it works. So, why?

PS: I normally compiled it with Gcc on Linux


Solution

  • Pure luck. The behavior in this case is undefined. I.e.: no expectations can be made as to what may happen.