Menu
Coddy logo textTech

Checking Allocation Failure

Part of the Logic & Flow section of Coddy's C journey — lesson 34 of 63.

While malloc() is a powerful tool for dynamic memory allocation, there's a critical reality you must understand: malloc() can fail. When the system runs out of available memory, malloc() cannot fulfill your request and returns NULL instead of a valid memory address.

This means that every time you use malloc(), you must check whether it succeeded before attempting to use the returned pointer. Using a NULL pointer will cause your program to crash with a segmentation fault.

int *ptr = (int*)malloc(sizeof(int));

if (ptr == NULL) {
    printf("Memory allocation failed!\n");
    return -1;  // Exit the program or handle the error
}

// Safe to use ptr here
*ptr = 42;

This NULL check is not optional - it's essential for writing robust C programs. Even if memory allocation failures are rare on modern systems, they can happen, especially in resource-constrained environments or when requesting large amounts of memory. Professional C code always includes these checks to prevent crashes and provide graceful error handling.

challenge icon

Challenge

Easy

Write a C program that demonstrates proper error handling when using malloc() for dynamic memory allocation. Your program should:

  1. Read an integer n from the user representing the number of integers to store
  2. Use malloc() with sizeof() to dynamically allocate memory for an array of n integers
  3. Check if the memory allocation was successful by testing if the returned pointer is NULL
  4. If allocation fails, print Memory allocation failed! and terminate the program
  5. If allocation succeeds, print Memory allocation successful!
  6. Read n integer values from the user and store them in the allocated array
  7. Calculate and print the sum of all values in the format: Sum: [value]
  8. Print the total bytes allocated in the format: Bytes allocated: [value]

Remember to include the <stdlib.h> header to use malloc(). Your program must demonstrate the essential practice of checking for allocation failure before attempting to use the allocated memory.

For example, if the input is:

4
10 20 30 40

Your output should be:

Memory allocation successful!
Sum: 100
Bytes allocated: 16

This challenge emphasizes the critical importance of defensive programming when working with dynamic memory allocation, ensuring your programs handle potential memory allocation failures gracefully rather than crashing unexpectedly.

Cheat sheet

Always check if malloc() returns NULL before using the allocated memory:

int *ptr = (int*)malloc(sizeof(int));

if (ptr == NULL) {
    printf("Memory allocation failed!\n");
    return -1;  // Exit the program or handle the error
}

// Safe to use ptr here
*ptr = 42;

malloc() can fail when the system runs out of available memory. Using a NULL pointer will cause a segmentation fault. This NULL check is essential for writing robust C programs and preventing crashes.

Try it yourself

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

int main() {
    // Read the number of integers
    int n;
    scanf("%d", &n);
    
    // TODO: Write your code here
    // - Use malloc() to allocate memory for n integers
    // - Check if allocation was successful
    // - Handle both success and failure cases
    // - Read the integers and store them
    // - Calculate the sum and bytes allocated
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow