free in c
Free in C
In C, the free
function is used to deallocate memory that was previously allocated using the malloc
, calloc
, or realloc
functions. Here's a step-by-step explanation of how the free
function works:
Check if the pointer is not NULL: Before calling
free
, it's important to ensure that the pointer being passed tofree
is not NULL. Attempting to free a NULL pointer can lead to undefined behavior.Release the allocated memory: When
free
is called with a valid pointer, it releases the memory block pointed to by the pointer, making it available for further allocation.Do not use the pointer after freeing: After calling
free
, the pointer should not be dereferenced. Doing so can lead to undefined behavior.Example: Here's an example of using the
free
function:
c
int ptr = (int )malloc(10 * sizeof(int)); // Allocate memory
// Check if allocation was successful
if (ptr != NULL) {
// Use the allocated memory
// ...
// Free the allocated memory when it's no longer needed
free(ptr);
}
After calling free(ptr)
, the memory previously allocated for ptr
is deallocated.