Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

Mastering C’s free() Function: Practical Guide & Example

What Is the free() Function in C?

The free() function, part of the C standard library, releases memory that was previously allocated with malloc(), calloc(), or realloc(). By returning the block to the heap, it keeps your program’s memory footprint under control and prevents exhaustion of available memory.

Unlike stack variables, dynamically allocated memory must be released explicitly. Failing to call free() can lead to memory leaks and eventually cause an out‑of‑memory error.

Syntax

void free(void *ptr);

Here, ptr is a pointer to the block of memory you wish to deallocate. Passing a NULL pointer is safe and results in no operation.

Practical Example

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

int main(void) {
    // Allocate space for 10 integers
    int *ptr = malloc(10 * sizeof(*ptr));

    if (ptr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    // Store a value and display it
    ptr[2] = 50;
    printf("Value of the 3rd integer is %d\n", ptr[2]);

    // Release the memory when done
    free(ptr);
    return 0;
}

Output:

Value of the 3rd integer is 50

Best Practices

C Language

  1. Using Impure Functions in VHDL: Enhancing FSM Readability and Maintainability
  2. Mastering VHDL Functions: A Practical Guide to Efficient Design
  3. C++ Polymorphism Explained: Practical Examples & Key Concepts
  4. Mastering C# Queues: Enqueue, Dequeue, and First‑In‑First‑Out Operations Explained
  5. Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
  6. calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
  7. Using realloc() in C: Syntax, Best Practices & Example
  8. Java HashMap: A Comprehensive Guide
  9. Mastering the 'this' Keyword in Java: Purpose, Usage, and Practical Examples
  10. Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples