Why do we check for a NULL pointer before deleting in C/C++?

In C programming, checking for a NULL pointer before calling free() is often seen in code, but it's technically unnecessary. The free() function is designed to safely handle NULL pointers by doing nothing when passed a NULL value.

Syntax

void free(void *ptr);

Why NULL Check is Unnecessary

According to the C standard, free(NULL) is guaranteed to be a no-op (no operation). This means the following code is redundant −

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

int main() {
    int *ptr = NULL;
    
    /* Redundant check */
    if (ptr != NULL) {
        free(ptr);
    }
    
    /* This is perfectly safe and equivalent */
    free(ptr);
    
    printf("Both approaches work safely with NULL pointers\n");
    return 0;
}
Both approaches work safely with NULL pointers

Example: Safe Memory Deallocation

Here's a practical example showing that free() handles NULL pointers gracefully −

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

int main() {
    int *ptr1 = malloc(sizeof(int) * 5);
    int *ptr2 = NULL;
    
    if (ptr1 != NULL) {
        *ptr1 = 42;
        printf("Allocated memory contains: %d\n", *ptr1);
    }
    
    /* Both calls are safe - no need for NULL checks */
    free(ptr1);  /* Frees allocated memory */
    free(ptr2);  /* Does nothing, but safe */
    
    printf("Memory freed successfully\n");
    return 0;
}
Allocated memory contains: 42
Memory freed successfully

When NULL Checks Might Indicate Issues

While NULL checks before free() are unnecessary, their presence might indicate potential bugs in program logic −

  • Double-free prevention: If you're checking for NULL to avoid freeing twice
  • Logic errors: Uncertainty about pointer state might suggest design problems
  • Defensive programming: Some developers prefer explicit checks for clarity

Best Practice

The recommended approach is to call free() directly without NULL checks, and set pointers to NULL after freeing to prevent accidental reuse −

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

int main() {
    int *ptr = malloc(sizeof(int) * 3);
    
    if (ptr != NULL) {
        ptr[0] = 10;
        printf("Value: %d\n", ptr[0]);
    }
    
    /* Free without NULL check */
    free(ptr);
    ptr = NULL;  /* Prevent accidental reuse */
    
    /* Safe to call again */
    free(ptr);
    
    printf("Safe memory management completed\n");
    return 0;
}
Value: 10
Safe memory management completed

Conclusion

Checking for NULL before free() is unnecessary since the function handles NULL pointers safely. However, such checks might indicate design issues that should be addressed for cleaner, more maintainable code.

Updated on: 2026-03-15T10:45:39+05:30

572 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements