YouTip LogoYouTip

C Function Free

## C Library Function - `free()` The `free()` function is a built-in C standard library function declared in ``. It is used to deallocate (release) memory blocks that were previously allocated dynamically using `malloc()`, `calloc()`, or `realloc()`. When dynamically allocated memory is no longer needed, calling `free()` releases it back to the system heap. This prevents memory leaks and ensures efficient memory management. --- ## Declaration The prototype for the `free()` function is as follows: ```c void free(void *ptr); ``` ### Parameters * **`ptr`**: This is the pointer to the memory block previously allocated with `malloc`, `calloc`, or `realloc` to be deallocated. If a null pointer (`NULL`) is passed as the argument, no action is performed. ### Return Value * This function does not return any value. --- ## Basic Example The following example demonstrates how to allocate, reallocate, and release memory using `malloc()`, `realloc()`, and `free()`. ```c #include #include #include int main() { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "youtip"); printf("String = %s, Address = %p\n", str, (void*)str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %p\n", str, (void*)str); /* Deallocate the allocated memory */ free(str); return 0; } ``` ### Output When you compile and run the program above, it produces the following output (addresses may vary): ```text String = youtip, Address = 0x7fe4e4c02b10 String = youtip.com, Address = 0x7fe4e4c02b10 ``` --- ## Memory Leaks and Dangling Pointers Improper dynamic memory management in C typically leads to two major issues: * **Memory Leak**: If dynamically allocated memory is not freed, or if the program loses the pointer referencing that memory, the memory remains occupied and cannot be reused. Over time, this can exhaust system memory and crash the application. * **Dangling Pointer**: A pointer that continues to point to a memory address after that memory has been freed is called a dangling pointer. Accessing or dereferencing a dangling pointer leads to undefined behavior, which can cause data corruption or segmentation faults. To prevent dangling pointers, it is highly recommended to set the pointer to `NULL` immediately after calling `free()`. --- ## Best Practices and Considerations ### 1. Free Only Dynamically Allocated Memory You must only pass pointers returned by `malloc()`, `calloc()`, or `realloc()` to `free()`. Passing pointers to local stack variables, global variables, or arbitrary memory addresses will cause runtime errors or crashes. ### 2. Avoid Double Freeing Freeing the same memory block more than once without an intervening allocation leads to undefined behavior (often a crash or security vulnerability). ```c free(ptr); // free(ptr); // ERROR: Double free! ``` ### 3. Nullify Pointers After Freeing Setting the pointer to `NULL` after freeing ensures you do not accidentally reuse a dangling pointer. ```c free(ptr); ptr = NULL; ``` ### 4. Safe Freeing Pattern While calling `free(NULL)` is safe and does nothing, checking for `NULL` explicitly before freeing and resetting the pointer is a robust defensive programming pattern: ```c if (ptr != NULL) { free(ptr); ptr = NULL; } ``` --- ## Comprehensive Example: Preventing Dangling Pointers The following complete program demonstrates how to safely allocate memory, use it, free it, and nullify the pointer to avoid dangling pointer issues. ```c #include #include int main() { // Dynamically allocate memory char *str = (char *)malloc(100 * sizeof(char)); if (str == NULL) { printf("Memory allocation failed\n"); return 1; } // Use the allocated memory safely snprintf(str, 100, "Hello, World!"); printf("%s\n", str); // Free the dynamically allocated memory free(str); // Set the pointer to NULL to prevent dangling pointer issues str = NULL; // Safely check if the pointer is NULL before any further operations if (str == NULL) { printf("str is now NULL and safe from dangling pointer issues.\n"); } return 0; } ``` ### Output ```text Hello, World! str is now NULL and safe from dangling pointer issues. ```
← C Function AtexitC Function Calloc β†’