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

569 views Asked by At

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

5

There are 5 answers

0
littleadv On BEST ANSWER

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

0
Anis_Stack On

you display the memory address of p before and after free to check "p" with :

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

    int main(void) {
        int *p = (int *)malloc(sizeof(int));
         printf("before \n %p \n",p);
         free(p);
        *p = 42;
         printf("after\n %p \n",p);
         printf(" %d \n",*p);
        return 0;
    }

before and after free we have the same address memory because free() don't assign NULL to p pointer, so *p = 42; work like static assignment although it's undefined behaviour.

suggest to use the FREE macro :

#define FREE(X) \
free(X);\
X=NULL;

test with this macro and you will see the expected behaviour

0
AudioBubble On

In my opinion it should not work [...] but it works.

Don't worry, it doesn't work.

it should cause a segmentation fault

Tell that to the C standards committee. It's just undefined behavior, it isn't required to crash.

0
Imran Ali Khan On

The behavior in this case is undefined ,

it is a possibility with undefin behavior

0
Harald On

The more elaborate answer beyond "undefined" is that you can write to arbitrary memory locations in C as long as you stay within the processes allocated memory areas. Depending on OS, overwriting code may be allowed or not. The ill effects only turn up, once some other code of your process gets confused by what is found at the garbled memory location. Since your program exits right away after messing up the memory, the chance for some of its code to get confused is obviously small.