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

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 the return for 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
πŸ’ͺ Not getting it first time is normal
Dynamic memory layers "borrow and return" responsibility on top of pointers β€” several ideas at once.
How to retry
  1. Review pointers if they're shaky
  2. Think "borrow (malloc) / return (free)" as a pair
  3. Start with small sizes (~10 elements) to build intuition
  4. Habit: set p = NULL; right after free
  5. A memory leak isn't an instant crash β€” you can proceed for now
πŸ’‘ Tip: Pair every malloc with a free, always null-check the return. That's enough for now.

Why Dynamic Memory?

Up to now, arrays have had their size fixed at compile time, as in int a[5];. But real programs often can't know the element count until runtime.
Fixed array limits
int a[100];
Can't hold more than 100 items. With fewer, memory is wasted.
With dynamic allocation
int *a = malloc(n * sizeof(int));
Allocate exactly n items; you can adjust the size as needed.

malloc and free

malloc allocates the requested number of bytes and returns a pointer to the start. When you're finished, 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 = 4 * 5 = 20 bytes. malloc allocates in bytes, so multiplying by sizeof is the standard idiom.

Dynamic Arrays β€” Size Decided at Runtime

A common pattern: ask the user for a count, then allocate an array of 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 if You Forget free

If you forget to free the memory you got from malloc, it stays reserved until the program ends. That's called a memory leak.
Memory leak simulation
Press the buttons to watch the memory change.
In long-running programs (servers, embedded systems), memory leaks are fatal. Even small leaks accumulate and eventually cause the program to run out of memory and crash. Make it a habit: if you malloc, you free.

Try It Yourself β€” Dynamic Memory

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

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 27: File I/O
Next lesson →
Lesson 29: Data Structures

Frequently Asked Questions

Q. Should I use malloc or an array?

A. Use an array when the size is known at compile time, and malloc when it is determined 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 possible.

Q. What happens if I forget to call free?

A. You get a memory leak. The allocated memory remains unusable, and in long-running programs memory gradually dwindles until the program runs out of memory and crashes. The rule is: if you malloc, you must free. Allocation and release must 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), e.g. calloc(10, sizeof(int)) allocates 10 ints initialized to zero.

Q. What exactly is a memory leak?

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

Quick Quiz

Check your understanding of this lesson.

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

It is automatically freed
A memory leak occurs
Compile error

Memory from malloc must be freed explicitly; otherwise it leaks.

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

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

sizeof(int) * 10 computes the byte size for 10 ints; 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 needs to be done

A pointer after free is a "dangling pointer." Setting it to NULL makes accidental reuse easy to detect.

Share this article
Share on X Share on Facebook