Search code examples
cpointersmallocheap-memoryfree

2 Ways of calling free - is there a difference?


Is there a difference between those two variants of calling free after allocating memory on the heap:

// variant 1
int* p1 = (int*) malloc(sizeof(int)*4);
free(p1);

//variant 2
int* p2 = (int*) malloc(sizeof(int)*4);
free(*p2);
*p2 = NULL;

Solution

  • Yes, there is a difference.

    Variant 2 is invalid. free expects a pointer previously returned by malloc, calloc, or realloc. *p2 is the first int in the allocated space, though. As man free says, undefined behavior occurs therefore (quotation adjusted for this specific case):

    free() function frees the memory space pointed to by [p1], which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, [...] undefined behavior occurs.


    Notes: