- It is a C library function that helps in freeing the memory.
- The behavior is undefined if ptr is not a pointer that has been returned by malloc(), calloc() or realloc() or if it has been already deallocated by realloc() or free().
- It does not return anything.
void free( void *ptr);
where ptr points to the memory to be freed.
int *ptr = (int*) malloc(8);
Once the pointer is freed, it must be set to NULL to avoid any accidental usage.
How does free work or why in free size is not given to be freed?
When we allocate memory, there is a special block that holds the metadata in the pointer variable and this metadata contains size of the memory allocated.
Thus when we use the pointer variable in the free(), we do not need to pass the size of the memory to be freed as malloc or calloc keeps track of size of each block as a metadata.
- Dynamic Memory Allocation
- Memory Allocators: brk() and sbrk()
- User defined malloc(), calloc(), realloc() and free()
- Interview questions on dynamic memory allocation
Categories: C Language
Leave a Reply