0
0
CHow-ToBeginner · 3 min read

How to Check if malloc Failed in C: Simple Guide

In C, you check if malloc failed by testing if the returned pointer is NULL. If it is NULL, the memory allocation failed and you should handle the error accordingly.
📐

Syntax

The malloc function allocates memory and returns a pointer to it. You must check if this pointer is NULL to detect failure.

  • void *malloc(size_t size); - requests size bytes of memory.
  • If allocation succeeds, returns a pointer to the allocated memory.
  • If allocation fails, returns NULL.
c
void *ptr = malloc(size_in_bytes);
if (ptr == NULL) {
    // handle allocation failure
}
💻

Example

This example shows how to allocate memory for 10 integers and check if malloc failed. If it fails, it prints an error message and exits.

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

int main() {
    int *arr = malloc(10 * sizeof(int));
    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1; // Exit with error
    }
    // Use the allocated memory
    for (int i = 0; i < 10; i++) {
        arr[i] = i * 2;
    }
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    free(arr); // Always free allocated memory
    return 0;
}
Output
0 2 4 6 8 10 12 14 16 18
⚠️

Common Pitfalls

Common mistakes when checking malloc failure include:

  • Not checking if the pointer is NULL before using it, which can cause crashes.
  • Assuming malloc never fails on small allocations.
  • Forgetting to free allocated memory, causing memory leaks.

Always check the pointer immediately after malloc and handle failure gracefully.

c
/* Wrong way: Not checking malloc result */
int *ptr = malloc(100 * sizeof(int));
ptr[0] = 10; // Unsafe if malloc failed

/* Right way: Check before use */
int *ptr2 = malloc(100 * sizeof(int));
if (ptr2 == NULL) {
    // Handle error
} else {
    ptr2[0] = 10; // Safe to use
}
📊

Quick Reference

Remember these tips when using malloc:

  • Always check if the returned pointer is NULL.
  • Use sizeof to calculate memory size.
  • Free allocated memory with free when done.
  • Handle allocation failure to avoid crashes.

Key Takeaways

Always check if malloc returns NULL to detect allocation failure.
Use sizeof to calculate the correct memory size for malloc.
Handle malloc failure gracefully to prevent program crashes.
Free allocated memory with free to avoid memory leaks.
Never use the pointer returned by malloc without checking it first.