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
EasyWrite a C program that demonstrates proper error handling when using malloc() for dynamic memory allocation. Your program should:
- Read an integer
nfrom the user representing the number of integers to store - Use
malloc()withsizeof()to dynamically allocate memory for an array ofnintegers - Check if the memory allocation was successful by testing if the returned pointer is
NULL - If allocation fails, print
Memory allocation failed!and terminate the program - If allocation succeeds, print
Memory allocation successful! - Read
ninteger values from the user and store them in the allocated array - Calculate and print the sum of all values in the format:
Sum: [value] - 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 40Your output should be:
Memory allocation successful!
Sum: 100
Bytes allocated: 16This 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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions6Memory Management
Stack vs. Heap MemoryDynamic Allocation - malloc()Using sizeof() for AllocationChecking Allocation FailureFreeing Memory with free()Allocating with calloc()Recap: Dynamic Array