Search code examples
cmemorymallocfree

Questions on use of malloc() and free()


Thanks for notice my question.

In C Primer Plus, it first writes

The argument to free() should be a pointer to a block of memory allocated by malloc(); you can’t use free() to free memory allocated by other means

which means ONE malloc(), ONE and ONLY one free().

But later it goes

It’s okay to use a different pointer variable with free() than with malloc(); what must agree are the addresses stored in the pointers.

which seems contradict to the first statement.

So my understanding is that as long as a pair of malloc() and free() share the same address there is no error, and the name of pointers doesn't matter. Am I right?


Solution

  • For example:

    void* p = malloc (100);
    void* q = p;
    free (q);
    

    ...is fine. The argument for free () is the value that was returned by malloc. The sentence

    "It’s okay to use a different pointer variable with free() than with malloc()"

    is actually pointless and just creates confusion - of course it is fine to use different variables as long as the value is the same.