0
0
Cprogramming~5 mins

free function

Choose your learning style9 modes available
Introduction

The free function is used to give back memory that was taken before. This helps your program not waste memory and run better.

When you have finished using a block of memory you got with <code>malloc</code> or <code>calloc</code>.
When you want to avoid your program using too much memory over time.
When you want to clean up memory before your program ends.
When you want to prevent your program from crashing due to running out of memory.
Syntax
C
void free(void *ptr);

The ptr must be a pointer you got from malloc, calloc, or realloc.

After calling free, the pointer ptr becomes invalid and should not be used again unless assigned a new value.

Examples
Allocate memory for one integer, then free it when done.
C
int *p = malloc(sizeof(int));
free(p);
Allocate memory for 10 characters initialized to zero, then free it.
C
char *name = calloc(10, sizeof(char));
free(name);
Sample Program

This program allocates memory for 5 integers, fills them with values, prints them, and then frees the memory.

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

int main() {
    int *numbers = malloc(5 * sizeof(int));
    if (numbers == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        numbers[i] = i * 10;
    }

    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    free(numbers); // Give back the memory

    return 0;
}
OutputSuccess
Important Notes

Always check if malloc or calloc returned NULL before using the memory.

Do not call free on memory that was not allocated dynamically or already freed.

Summary

free returns memory you no longer need back to the system.

Use it after malloc, calloc, or realloc to avoid memory waste.

Never use the pointer after freeing it without assigning new memory.