Function free() in C isn't working for me

前端 未结 5 672
无人共我
无人共我 2020-12-18 17:25

I have been trying to free memory allocated via malloc() using free().

Some of the structs it does free but leaves some the way they were a

5条回答
  •  别那么骄傲
    2020-12-18 17:53

    First, free does not change the pointer itself.

    void *x = malloc(1);
    free(x);
    assert(x != NULL); // x will NOT return to NULL
    

    If you want the pointer to go back to NULL, you must do this yourself.

    Second, there are no guarentees about what will happen to the memory pointed to by the pointer after the free:

    int *x = malloc(sizeof(int));
    *x = 42;
    free(x);
    // The vlaue of *x is undefined; it may be 42, it may be 0,
    // it may crash if you touch it, it may do something even worse!
    

    Note that this means that you cannot actually test if free() works. Strictly speaking, it's legal for free() to be implemented by doing absolutely nothing (although you'll run out of memory eventually if this is the case, of course).

提交回复
热议问题