Understanding malloc: How C Really Gets Memory
If you are learning C, sooner or later you will meet a function called malloc.
Understanding malloc: How C Really Gets Memory

If you are learning C, sooner or later you will meet a function called malloc.
And when you do, it often feels confusing, scary, or unnecessarily low-level.
Questions like these are very common:
Why do I need malloc?
What does it really do?
Why does it return a pointer?
Why does everyone warn me about “memory leaks”?
This article explains malloc from first principles, using intuition, simple code, and common mistakes , so you can actually understand it, not just memorize syntax.
Outline
- Why Do We Even Need malloc?
- What Is malloc, in One Sentence
- The Basic Syntax of malloc
- What Actually Happens in Memory?
- Accessing the Allocated Memory
- The Most Common Beginner Mistakes (Read This Carefully)
- malloc vs calloc
- Why Does malloc Return void *?
- Freeing Memory Is NOT Optional
- When Should Beginners Use malloc?
- One-Minute Mental Model
- A Simple, Correct Example
- Quiz: Debugging Challenges
1. Why Do We Even Need malloc?
Before malloc, let’s talk about memory.
In C, you mainly deal with two kinds of memory: stack and heap.
Stack Memory (Automatic)
int a[10];
- Size is fixed at compile time
- Automatically allocated and freed
- Fast and safe
- Limited in size
Heap Memory (Dynamic)
This is where malloc comes in.
Heap memory is used when:
- You don’t know the size in advance
- The data must live longer than a function call
- You need flexible data structures (lists, trees, buffers)
A Simple Analogy
- Stack → Your desk drawer (small, fast, fixed)
- Heap → A warehouse where you request space when needed
If your program needs memory while running, the stack alone is not enough. You need the heap.
2. What Is malloc, in One Sentence
mallocasks the operating system for a block of memory at runtime and returns a pointer to it.
That’s it.
Nothing more magical than that.
3. The Basic Syntax of malloc
Here is the most common example:
int *p = malloc(4 * sizeof(int));
Let’s break this down slowly.
sizeof(int)
- Size of one
int(usually 4 bytes)
4 * sizeof(int)
- Total memory requested
- Enough space for 4 integers
malloc(...)
- Allocates memory from the heap
- Returns a pointer to the first byte of that memory
int *p
- A pointer that stores the address of the allocated memory
The Golden Rule:
type *ptr = malloc(n * sizeof(type));
Memorize this pattern — it will save you from many bugs.
4. What Actually Happens in Memory?
Consider this code:
int *p = malloc(3 * sizeof(int));
Before malloc
pexists- The memory it points to does not
After malloc
ppoints to a block of heap memory- The memory contains garbage values
Conceptually:
Stack: p ───────►
Heap: [ ? | ? | ? ]
⚠️ Important:
malloc does not initialize memory.
If you read from it before writing, you get undefined behavior.
5. Accessing the Allocated Memory
Once allocated, you can use it like an array:
p[0] = 10;
p[1] = 20;
p[2] = 30;
This works because:
p[i] ≡ *(p + i)
C treats allocated memory and arrays almost the same , but only if you stay within bounds.
6. The Most Common Beginner Mistakes (Read This Carefully)
❌ Mistake 1: Forgetting sizeof
int *p = malloc(4); // WRONG
Why this is bad:
- Assumes
intis always 4 bytes - Breaks portability
- Causes memory corruption
Correct:
int *p = malloc(sizeof(int));
❌ Mistake 2: Not Checking for NULL
malloc can fail.
int *p = malloc(1000000000 * sizeof(int));
If memory cannot be allocated, malloc returns NULL.
Always check:
if (p == NULL) {
// handle error
}
❌ Mistake 3: Using Memory After free
free(p);
p[0] = 10; // Undefined behavior
This is called a dangling pointer.
Safe practice:
free(p);
p = NULL;
❌ Mistake 4: Memory Leaks
void foo() {
int *p = malloc(100 * sizeof(int));
// forgot free
}
- Memory is allocated
- Never returned
- Repeated calls = disaster
Rule of thumb:
Every
mallocmust have exactly onefree.
7. malloc vs calloc

Example:
int *p = calloc(4, sizeof(int));
Use calloc when:
- You want clean, zeroed memory
- Initialization matters
8. Why Does malloc Return void *?
malloc returns a generic pointer:
void *malloc(size_t size);
This allows it to allocate memory for any type.
In C:
int *p = malloc(sizeof(int)); // casting NOT required
⚠️ Do not cast malloc in C:
int *p = (int *)malloc(sizeof(int)); // discouraged
Casting can hide bugs if headers are missing.
9. Freeing Memory Is NOT Optional
free(p);
What free does:
- Returns memory to the heap
- Makes it reusable
- Does not delete the pointer variable
Best practice:
free(p);
p = NULL;
This prevents accidental reuse.
10. When Should Beginners Use malloc?
Use malloc when:
- Size is determined at runtime
- Data must outlive a function
- Implementing dynamic data structures
Avoid malloc when:
- Fixed-size arrays are enough
- Stack memory is sufficient
- Performance-critical embedded paths (unless necessary)
11. One-Minute Mental Model
malloc→ reserve memory
Pointer → access memory
free→ release memory
Forget
free→ memory leak
Use after
free→ undefined behavior
If you remember only this, you are already ahead of many beginners.
12. A Simple, Correct Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *p = malloc(n * sizeof(int));
if (p == NULL) {
return 1;
}
for (int i = 0; i < n; i++) {
p[i] = i * 10;
}
for (int i = 0; i < n; i++) {
printf("%d ", p[i]);
}
free(p);
p = NULL;
return 0;
}
13. Quiz: Debugging Challenges
Let’s test your understanding.
Each snippet below compiles, but something is wrong or dangerous. Try to identify the issue before reading the explanation.
Quiz 1: The Silent Time Bomb
int *p = malloc(10);
p[0] = 42;
Question: What is wrong with this code? (Answer is on the comment section)
Quiz 2: It Works… Until It Doesn’t
int *p = malloc(100 * sizeof(int));
free(p);
p[0] = 5;
Question: Why is this dangerous? (Answer is on the comment section)
Quiz 3: The Invisible Leak
void process() {
int *p = malloc(50 * sizeof(int));
// do something
}
Question: What is the problem here? (Answer is on the comment section)
Quiz 4: The Sneaky Crash
int *p = malloc(1000000000 * sizeof(int));
p[0] = 1;
Question: Why might this crash on some machines?
(Answer is on the comment section)
Quiz 5: The Illusion of Safety
int *p = malloc(5 * sizeof(int));
printf("%d\n", p[0]);
Question: Why is this UNSAFE? (even though nothing “looks wrong”)
(Answer is on the comment section)
Quiz 6: Final Question
int *p = malloc(sizeof(int));
*p = 10;
free(p);
p = malloc(sizeof(int));
printf("%d\n", *p);
Question: What will this print? (Answer is on the comment section)
Final Takeaway
If you can correctly answer these questions, you:
- Understand
mallocbeyond syntax - Can debug real C programs
- Are already thinking like a systems programmer
If you found this quiz useful, try running these snippets with valgrind or AddressSanitizer. Seeing the errors reported is one of the fastest ways to master memory management in C.
Thanks for reading! Hopefully you got the core idea.
Comments down below if you have any questions. I will be glad to reply to every questions.
Let’s stay in touch:
🔗 Medium: Follow → Eka Gunawan
🔗 LinkedIn: Connect for career and job strategy → [linkedin.com/in/eka-gun-tw/]
Tag a friend who’s scared of C programming
메타데이터
- post_id
- 7faf708f5e92
- slug
- understanding-malloc-how-c-really-gets-memory-7faf708f5e92
- url
- https://medium.com/@send.raden/understanding-malloc-how-c-really-gets-memory-7faf708f5e92
- canonical_url
- https://medium.com/@send.raden/understanding-malloc-how-c-really-gets-memory-7faf708f5e92
- author_url
- https://medium.com/@send.raden
- status
- ok
- fetched_at
- 2026-06-24 23:31:39