My friend and I had a discussion over freeing dynamically allocated memory. He told that a memory could be freed with realloc(), to which I denied. Let's consider the below code:
int main()
{
int *p = (int *)malloc(sizeof(int) * 10);
int *q = (int *)malloc(sizeof(int) * 10);
free(p);
p = NULL;
realloc(q, sizeof(int) * 0);
q = NULL;
_getch();
return 0;
}
Let's assume p and q are pointing to address 0x1000
& 0x2000
respectively.
In the above code, p and q are int
pointers pointing to dynamically allocated 40 bytes of memory blocks in the RAM. On executing free(p)
frees the memory address (0x1000
). The freed memory address (0x1000
) could be used by an OS again. Then, NULL is assigned to pointer variable p
to prevent p
of becoming a dangling pointer.
realloc(q, sizeof(int) * 0);
realloc()
simply shrinks the memory block pointed by q to zero. But q still points to the same address (0x2000
), and that address is not freed. On assigning NULL value to pointer q, q now points to NULL and the address (0x2000
) to which q was pointing is not freed and the link to that address (0x2000
) is lost. That address (0x2000
) cannot be used by OS in the future until the end of the program.
Is my understanding correct?