- How to allocate memory at runtime with
malloc() - How to check for a
NULLreturn and handle allocation failure - How to read elements into a dynamically allocated array
- How to accumulate the sum of all elements
- How to release memory with
free()to avoid leaks
Objective & Purpose
Objective: The fundamental objective of this program is to show how to dynamically allocate memory for an array of integers in C and to compute the sum of all elements in that array.
Purpose: This program explains the concept of dynamic memory allocation in C and how it is used to work with arrays of integers. With dynamic memory allocation, a program can adjust the size of an array at runtime, making it more flexible and effective.
💡 Quick Definition: Dynamic Memory Allocation (DMA) means asking the operating system for memory at runtime using functions like malloc(), calloc(), realloc(), and returning it with free().
Real-life applications of dynamic memory allocation include managing large data sets, implementing data structures such as linked lists and trees, and optimizing memory utilization in resource-constrained environments.
What is Dynamic Memory Allocation?
In C, static arrays have a fixed size determined at compile time. If you don't know how many elements you'll need until the program runs, you need dynamic memory.
The malloc() function (from <stdlib.h>) requests a contiguous block of bytes from the heap and returns a void * pointer to it. You then cast it to the appropriate type. If allocation fails (out of memory), malloc returns NULL — always check for that.
| Function | Signature | Purpose |
|---|---|---|
malloc | void *malloc(size_t bytes) | Allocates an uninitialized block of bytes |
calloc | void *calloc(size_t n, size_t size) | Allocates n × size bytes and zero-initializes |
realloc | void *realloc(void *ptr, size_t size) | Resizes an existing block |
free | void free(void *ptr) | Releases a block back to the OS |
Complete C Program
Program: Dynamically allocate an array of integers and display the sum
#include <stdio.h>
#include <stdlib.h>
int main()
{
int size, i, *arr, sum = 0;
/* ask the user for the array size */
printf("\nEnter the size of the array: ");
scanf("%d", &size);
/* allocate memory dynamically */
arr = (int *)malloc(size * sizeof(int));
/* check whether allocation succeeded */
if (arr == NULL)
{
printf("\nUnable to allocate memory!\n");
return 1;
}
/* read the elements */
printf("\nEnter %d elements:\n", size);
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
/* compute the sum of all elements */
for (i = 0; i < size; i++)
{
sum += arr[i];
}
/* display the result */
printf("\nThe sum of all elements in the array is = %d\n", sum);
/* release the memory */
free(arr);
arr = NULL;
return 0;
}
Program Output
Enter the size of the array: 5
Enter 5 elements:
11
12
13
14
15
The sum of all elements in the array is = 65
Step-by-Step Explanation
Let's break down this program line by line to understand what's happening:
1. Inclusion of header files:
#include <stdio.h>
#include <stdlib.h>
stdio.h gives us printf and scanf. stdlib.h gives us malloc and free.
2. Variable Declaration:
int size, i, *arr, sum = 0;
size holds the number of elements, i is the loop counter, *arr will point to the heap block, and sum starts at 0. The loop counter is declared up front so the code stays C89-compatible.
3. Ask the user for the size:
printf("\nEnter the size of the array: ");
scanf("%d", &size);
The size is not known at compile time — this is exactly why we need dynamic allocation.
4. Allocate memory with malloc:
arr = (int *)malloc(size * sizeof(int));
size * sizeof(int) calculates the total number of bytes needed. On most platforms sizeof(int) == 4, so for 5 elements we ask for 20 bytes. The cast (int *) converts the void * returned by malloc into an int *.
5. Check for NULL:
if (arr == NULL)
{
printf("\nUnable to allocate memory!\n");
return 1;
}
If malloc couldn't allocate the block, it returns NULL. Using a NULL pointer is undefined behavior — so we bail out gracefully instead.
6. Read elements into the array:
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
arr[i] is pointer arithmetic — arr[i] is equivalent to *(arr + i). The & gives the address of each element for scanf.
7. Compute the sum:
for (i = 0; i < size; i++)
{
sum += arr[i];
}
sum += arr[i] is the compound form of sum = sum + arr[i]. For elements 11, 12, 13, 14, 15 the running total becomes 11 → 23 → 36 → 50 → 65.
8. Display the result and free the memory:
printf("\nThe sum of all elements in the array is = %d\n", sum);
free(arr);
arr = NULL;
free(arr) returns the heap block to the operating system. Setting arr = NULL afterward prevents accidental use-after-free bugs.
Key Takeaways
| Rule | Why it matters |
|---|---|
Always check malloc for NULL | Prevents crashes on low-memory systems |
Match every malloc with a free | Prevents memory leaks |
Set pointers to NULL after free | Prevents dangling pointers |
Use n * sizeof(type), not hardcoded numbers | Portable across platforms |
Never dereference the return value of malloc before checking it | Avoids undefined behavior |
🎯 Key Takeaway: Dynamic memory problems are not hard because of the logic — they're hard because of lifecycle discipline. Allocate → check → use → free. Follow that order and you'll never leak memory.
Frequently Asked Questions
1. Why do we need dynamic memory for this array?
Because the number of elements isn't known until runtime. A fixed-size array would either be too small (causing errors) or waste memory.
2. What happens if malloc returns NULL?
If allocation fails, malloc returns NULL. Dereferencing a NULL pointer crashes the program. This is why every malloc call must be checked.
3. Do I need to cast the result of malloc?
In C, it's not strictly required — void * implicitly converts to any pointer type. But casting (int *)malloc(...) is common practice and keeps the code compatible with C++ compilers.
4. What if I forget to call free()?
You get a memory leak. The program keeps the block reserved until it exits. For long-running programs (servers, daemons), leaks accumulate and eventually exhaust memory.
💡 Tip: Compile with gcc -fsanitize=address -g program.c to catch leaks and use-after-free bugs instantly.