문제

I wanted to ask, if I have a pointer pointing at some struct, but then I free(struct) then if I dereference the pointer, will it be pointing to NULL? As in can I check, pointer != NULL or is this undefined?

Thanks!

도움이 되었습니까?

해결책

Calling free() on the pointer does not change the pointer value. It will still point to the same memory that no longer belongs to your application. You should always assign NULL to a free'd pointer immediately after you free it to ensure that you don't use it again.

void *p = malloc(10);    // p points to allocated memory
free(p);                 // p still points to invalid memory
p = NULL;                // good practice

다른 팁

Consider the below code

int main()
{
    int *p = (int *)malloc(sizeof(int) * 10);
    free(p);
}

Here variable p is a local variable of a function main. Size of this variable will be 4 bytes(in 32bit m/c) or 8 bytes(in 64 bit m/c). Now we are allocating memory for storing 10 integer elements and that address is stored in variable p. Now we are calling free function to which we are passing the dynamic memory address which is stored in the local variable p. Now free function will free the memory and it will not be able to assign NULL to the variable p. Because we passed address as value, not reference to the pointer.

We can define a wrapper function for free like below

void myfree(void **p)
{
    free(*p);
    *p = NULL;
}

int main()
{
    int *p = (int *)malloc(sizeof(int) * 10);
    myfree(&p);
}

Or we can define macro function also

#define MYFREE(x) \
        free(x); \
        x = NULL; 

It's undefined. C does not define what it does with the contents of the pointer, although most implementations do nothing.

Take a look at this page.

It clearly says:

Notice that this function leaves the value of ptr unchanged, hence it still points to the same (now invalid) location, and not to the null pointer.

Note that it is up to you to make sure that pointer is not dereferenced after being freed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top