C Dynamic Memory — malloc, calloc, realloc, and free
Learning Objectives
- Allocate memory on the heap at runtime
- Choose between malloc, calloc, and realloc
- Release memory with free and prevent leaks
- Check allocation results before using memory
Stack Versus Heap Memory
Local arrays and variables live on the stack and disappear when their function returns. Their size must usually be known at compile time. The heap is a separate pool of memory that your program can request and release while it runs. Dynamic allocation is how C programs build lists, buffers, and data structures whose sizes depend on user input.
You request heap memory through functions declared in the standard library. You are responsible for releasing every block you successfully allocate. Forgetting that duty causes memory leaks that grow over time.
Allocating with malloc
The malloc function asks for a contiguous block of a given number of bytes. It returns a generic pointer on success or null when the request cannot be satisfied. You cast the result to the pointer type your program needs.
#include
#include
int main(void) {
int *nums = malloc(5 * sizeof(int));
if (nums == NULL) {
printf("Allocation failed.\n");
return 1;
}
for (int i = 0; i < 5; i++) {
nums[i] = (i + 1) * 10;
}
printf("%d\n", nums[2]);
free(nums);
return 0;
}
The expression five times sizeof of int computes the exact byte count for five integers. Always derive sizes with sizeof instead of hardcoding numbers, because type sizes vary across platforms.
calloc and realloc
calloc allocates and zeroes the block in one step, which is helpful when leftover garbage values would be dangerous. realloc grows or shrinks an existing block while preserving as much of the old data as fits.
| Function | Behavior |
|---|---|
| malloc | Allocates uninitialized bytes |
| calloc | Allocates and sets every byte to zero |
| realloc | Resizes a previous block, may move it |
| free | Releases a block back to the heap |
int *row = calloc(10, sizeof(int));
row = realloc(row, 20 * sizeof(int));
free(row);
When realloc moves the block, it returns a new address and the old address becomes invalid. Always assign the result to a temporary pointer first so you can detect failure without losing the original block.
Freeing Memory
Calling free marks a heap block as reusable. After freeing, the pointer still holds the old address, but that address must not be used again. This is called a dangling pointer. Good practice sets the pointer back to null immediately after free so accidental reuse is easier to spot.
free(nums);
nums = NULL;
Freeing the same block twice corrupts the allocator and often crashes the program. Track ownership clearly so only one part of the code releases each pointer.
⚠️Allocation Can Fail
Production programs must handle allocation failure. Check for null after every dynamic allocation and provide a graceful exit or fallback path when memory is unavailable.
Memory Leaks
A leak happens when a program loses the ability to free memory it allocated. Overwriting the only pointer to a block without freeing it first is the most common cause. Long-running services that leak gradually can exhaust memory and fail in production.
Build the habit of pairing every allocation with a plan for release. For simple programs, free before returning from main. For complex designs, document which function owns each pointer and when ownership transfers.
Common Heap Mistakes
Using memory before checking the allocation result risks a null dereference. Writing past the requested size corrupts heap metadata. Mixing pointers from malloc with pointers from calloc is fine after allocation, but mixing stack addresses into free calls is never acceptable.
Another subtle issue is allocating with the wrong element count, such as requesting space for a few bytes when you meant a few elements. Multiplying count by sizeof is the correct formula almost every time.
Key Takeaways
💡
- Heap memory lives until you free it, unlike automatic stack variables
- malloc allocates raw bytes, calloc zeroes them, realloc resizes
- Always check dynamic allocation for a null result
- free releases memory once; double free is a serious bug
- Set pointers to null after free to reduce dangling pointer risk
Practice Questions
- Why should you use sizeof when computing malloc byte counts?
- What happens if realloc fails and why should you use a temporary variable?
- Define a memory leak and describe one common way beginners cause one.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions