C Deallocate Memory

Deallocating memory is essential to prevent memory leaks. The free() function is used to release dynamically allocated memory back to the system.

Key Topics

1. Using free()

Example: Deallocating Memory

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr = (int *)malloc(sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    *ptr = 50;
    printf("Value: %d\n", *ptr);

    free(ptr); // Free the memory
    ptr = NULL; // Avoid dangling pointer

    return 0;
}

Code Explanation: The free() function releases the memory allocated to ptr. Setting ptr to NULL prevents it from becoming a dangling pointer.