Initial memory allocation with malloc
What you'll learn: How to use malloc to request a specific block of memory from the heap to store an array whose size is determined at runtime.
The problem with fixed sizes
Up until now, you have likely created arrays like this: int scores[10];. This is simple, but it has a major drawback: the size is locked in before the program even runs. If you suddenly need to store 11 scores, your program crashes or behaves unpredictably. To build a "dynamic" array—one that can grow or shrink—we first need to learn how to grab a flexible chunk of memory from the "Heap," a large pool of free memory managed by the operating system.
Using malloc for the first slice
The malloc function (short for "memory allocation") is your tool for this. Think of it like calling a warehouse and saying, "I need enough shelf space for 50 boxes." The warehouse doesn't care what is in the boxes; it just needs to know the total physical space required.
To use malloc, you must tell it exactly how many bytes you want. Since different data types (like int or double) take up different amounts of space, we use the sizeof operator to ensure we get the math right.
Seeing it in code
Here is how you allocate space for an array of integers where the size is decided by a variable:
#include <stdio.h>
#include <stdlib.h> // Required for malloc and free
int main() {
int n = 5; // This could be user input!
// 1. Request memory for 'n' integers
// We multiply the number of elements by the size of one element
int *arr = malloc(n * sizeof(int));
// 2. Check if the memory was actually granted
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// 3. Use it just like a normal array
for (int i = 0; i < n; i++) {
arr[i] = i * 10;
printf("%d ", arr[i]);
}
// 4. Always clean up when finished
free(arr);
return 0;
}
Why the NULL check matters?
When you call malloc, it returns a pointer to the start of the memory block. However, if your computer is completely out of memory, malloc will return NULL. Always check for this! Attempting to write data to a NULL pointer is a one-way ticket to a program crash.
By using malloc, you’ve taken the first step toward building data structures that adapt to the user's needs rather than forcing the user to fit into a fixed-size box.
Key takeaway
Use malloc(count * sizeof(type)) to reserve a block of heap memory, and always check if the resulting pointer is NULL before using it.