C free() Function

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is free() Function?

void free(void *ptr) returns a block from malloc, calloc, or realloc to the allocator. Pass only pointers that were returned by those functions (or NULL, which is safe). Freeing the same pointer twice, or a pointer not from the allocator, is undefined behavior.

Remember
free(p);
p = NULL;       /* avoid dangling pointer and double free */
free(NULL);     /* legal: does nothing */

Cheat Sheet

Keep these facts handy while you work with free() Function in C.

TopicDetail
ArgumentPointer from an allocator, or NULL
After freeDo not read, write, or free again
HabitSet to NULL
OwnershipOnly the owner frees

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Dynamic Arrays.

Example 1 — Copy a string to the heap and free it

The pointer is reset so accidental reuse is caught.

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

int main(void) {
    char *s = malloc(6);
    if (!s) return 1;
    strcpy(s, "hello");
    printf("%s\n", s);

    free(s);
    s = NULL;
    free(s);              /* harmless: free(NULL) does nothing */
    printf("freed\n");
    return 0;
}

How It Works

  1. Six bytes hold hello plus the terminator.
  2. free(s) releases the block.
  3. A NULL pointer can be passed to free again without error.

Edge Cases & Pitfalls

Check these before relying on free() Function in real programs.

double

Double free

Freeing a pointer twice corrupts the heap. Setting to NULL makes the second call harmless.

stack

Freeing non-heap memory

free(&x) or free(arr) on a stack array is undefined behavior.

Key Takeaways

  • Once: one free per allocation.
  • Reset: assign NULL afterward.
  • Only heap pointers.

One line: void free(void *ptr) returns a block from malloc, calloc, or realloc to the allocator.

Frequently Asked Questions

It is undefined behavior and often crashes or corrupts the heap. Set the pointer to NULL after freeing to avoid it.
No. free(NULL) is defined to do nothing.
Continue with "C Dynamic Arrays" next. Build a resizable array that doubles its capacity as it fills. The C Dynamic Memory Allocation hub lists every topic in order.

Next: Dynamic Arrays

Build a resizable array that doubles its capacity as it fills.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful