🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

C Dynamic Memory — malloc, calloc, realloc, free

C FundamentalsC Dynamic Memory🟢 Free Lesson

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.

FunctionBehavior
mallocAllocates uninitialized bytes
callocAllocates and sets every byte to zero
reallocResizes a previous block, may move it
freeReleases 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

  1. Why should you use sizeof when computing malloc byte counts?
  2. What happens if realloc fails and why should you use a temporary variable?
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert C Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement