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

5

0

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

Gaiser answered 21/12, 2013 at 21:23 Comment(3)
You were unlucky. Always a possibility with undefined behaviour.Kentiggerma
Not an exact duplicate since that question is tagged C++, but see #6441718Biamonte
Please read https://mcmap.net/q/53543/-what-is-a-segmentation-faultSweep
C
13

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

Chesney answered 21/12, 2013 at 21:24 Comment(0)
V
3

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.

Valles answered 21/12, 2013 at 21:24 Comment(0)
A
1

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.

Alvinaalvine answered 21/12, 2013 at 21:31 Comment(0)
G
0

The behavior in this case is undefined ,

it is a possibility with undefin behavior

Gathering answered 21/12, 2013 at 21:26 Comment(0)
L
-1

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

Labrador answered 21/12, 2013 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.