πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English

Dynamic Memory (malloc / free)

Dynamic allocation in C: malloc, free, and how to prevent memory leaks.

πŸ“– What to learn on this page
βœ… Must-know essentials
  • malloc(bytes) to allocate, free(p) to release
  • Check whether the return value is NULL
  • Every allocation must be freed
⭐ Read if you have time
  • calloc (zero-init), realloc (resize)
  • Memory leaks and detectors
  • Avoid dangling: set p = NULL; after free
πŸ’ͺ It's normal not to get it on the first try
Dynamic memory adds a "borrow and return" responsibility on top of pointers, so it's several ideas at once.
How to come back to it
  1. Review pointers if you still feel shaky on them
  2. Think of malloc (borrow) and free (return) as a pair that must always match
  3. Start with small sizes β€” around 10 elements β€” to build up your intuition
  4. Build the habit of setting p = NULL; right after calling free
  5. A memory leak won't crash your program instantly, so don't let it block your progress
πŸ’‘ Tip: pair every malloc with a free, and always null-check the return value. That's enough to get you started.

Why do we need dynamic memory?

Up to this point, arrays have had their size fixed at compile time, as in int a[5];. But in real-world programs, you often don't know the element count until runtime.
The fixed-array limitation
int a[100];
Can't hold more than 100 items, and if you have fewer, the remaining memory is wasted.
With dynamic allocation
int *a = malloc(n * sizeof(int));
Allocate exactly n items; use realloc if you need to resize later.

malloc and free

malloc allocates the number of bytes you ask for and returns a pointer to the start of that block. When you're done with it, release it with free.
#include<stdlib.h>  // needed for malloc, free

int *p = (int *)malloc(sizeof(int) * 5);
// allocate space for 5 ints (= 20 bytes)

if(p == NULL){
  printf("allocation failed\n");
  return 1;
}

// use it like an array
for(int i = 0; i < 5; i++){
  p[i] = i * 10;
}

free(p);  // always release when done
sizeof(int) * 5 is 4 Γ— 5 = 20 bytes. malloc works in bytes, so multiplying by sizeof is the standard idiom.

Dynamic arrays β€” size decided at runtime

A common pattern is to ask the user for a count, then allocate an array of exactly that size.
int n;
printf("How many? ");
scanf("%d", &n);

int *data = (int *)malloc(sizeof(int) * n);
if(data == NULL) return 1;

for(int i = 0; i < n; i++){
  printf("Item %d: ", i+1);
  scanf("%d", &data[i]);
}

// compute the sum
int sum = 0;
for(int i = 0; i < n; i++) sum += data[i];
printf("Sum: %d\n", sum);

free(data); // do not forget to free
p[i] and *(p + i) mean the same thing β€” a pointer from malloc can be indexed with [] just like an array.

Memory leaks β€” what happens when you forget to free

If you forget to free memory you got from malloc, that memory stays reserved until the program ends. This is called a memory leak.
Memory leak simulation
Click the buttons to watch the memory change.
In long-running programs (servers, embedded systems, and so on), memory leaks are fatal. Even small leaks accumulate over time and eventually exhaust memory, crashing the program. Make it a habit: if you malloc, you free.

πŸ”₯ Heap timeline — visualize the malloc/free flow

Watch how the heap changes as you call malloc and free. Step through five scenarios to see the classic bugs: double-free, use-after-free, memory leaks, and fragmentation.
πŸ§ͺ Pick a scenario
Pick a scenario to start.
// No scenario selected
Heap state
In use: 0 B Peak: 0 B malloc: 0 free: 0
Operation log
(Pick a scenario and press β–Ά)
πŸ’‘ How to read it: each block shows its ID, address, size, and state (🟒 in-use or πŸ”΄ freed). Illegal operations like double-free or use-after-free are flagged in red.

Try it yourself β€” dynamic memory

Allocate a dynamic array, fill it with values, and compute their sum.
dynamic.c
Output
Click Run...
πŸ’‘ Try these ideas too

Related lessons

Advanced
Pointer Basics
Understand pointers with memory visualization.
Algorithms
Data Structures
Linked list, stack, and queue β€” implementation and visualization.
Reference
Runtime Errors & Segfaults
Causes of segmentation faults and how to debug runtime errors.
← Previous lesson
Lesson 29: File I/O
Next lesson →
Lesson 31: Data Structures

Frequently Asked Questions

Q. Should I use malloc or an array?

A. Use a plain array when the size is known at compile time, and malloc when the size is only known at runtime. If you know the maximum is 100, use an array; if the user enters the count, use malloc. Arrays are generally faster and safer, so prefer them when you can.

Q. What happens if I forget to call free?

A. You get a memory leak. The allocated memory becomes unreachable, and in long-running programs the available memory gradually dwindles until the process runs out of memory and crashes. The rule is simple: if you malloc, you must free. Allocation and release always need to be paired.

Q. What is the difference between malloc and calloc?

A. malloc allocates the requested size but leaves the memory uninitialized. calloc zeros the memory for you. Its signature is calloc(count, size) β€” for example, calloc(10, sizeof(int)) allocates 10 ints, all initialized to zero.

Q. What exactly is a memory leak?

A. A memory leak is memory that was allocated but never freed β€” it stays wasted until the program exits. A single leak rarely matters, but leaks inside a loop pile up and eventually exhaust memory. Tools like valgrind --leak-check=full are commonly used to detect them.

Review Quiz

Check your understanding of this lesson.

Q1. What happens if you never free memory obtained from malloc?

It's automatically freed
A memory leak occurs
Compile error

Memory from malloc must be freed explicitly. If you forget, it leaks.

Q2. What does malloc(sizeof(int) * 10) do?

Allocates enough space for 10 ints
Allocates enough space for 1 int
Allocates exactly 10 bytes

sizeof(int) * 10 computes the byte size for 10 ints, and malloc allocates that many bytes on the heap.

Q3. What should you do with a pointer right after calling free?

Keep using it
Assign NULL to it
Nothing more is needed

After free, the pointer becomes a "dangling pointer." Setting it to NULL makes any accidental reuse easy to detect.

Share this article
Share on X Share on Facebook