Вопрос

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

Это было полезно?

Решение

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

Другие советы

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.

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.

The behavior in this case is undefined ,

it is a possibility with undefin behavior

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top