Reflection on C and C++ Memory Allocation Difference
When I was coding in C at uni, I was always confused about how to manage memory manually. Although I used malloc() and realloc(), I’m a bit rusty on how they work now. And you know, what’s learned from textbook and slides always feels shallow – even back then, I didn’t deeply and thoroughly understand those things.
So I’ve decided to work it out and strengthen my comprehension and memory by logging this brainstorming and learning process — and, by the way, augmenting it by implementing C++’s delete and new using lower-level C techniques.
What is malloc() ,calloc() and realloc()
Stack vs Heap in C and C++
Stack
- A region of memory that stores local variables and function call information.
- Managed automatically by the compiler.
Key properties:
- Fast allocation and deallocation (LIFO – last-in, first-out)
- Memory is freed automatically when the function returns
- Limited in size (usually a few megabytes)
- No need to call
free()ordelete
Examples:
C
1 | void func() { |
C++
1 | void func() { |
Heap
- A region of memory used for dynamic allocation.
- Managed manually by the programmer.
Key properties:
Allocated using functions like
malloc()/calloc()(in C) ornew(in C++)Must be manually deallocated using
free()(in C) ordelete(in C++)Memory stays allocated until explicitly freed
Useful when size or lifetime of data is not known at compile time
A region of memory used for dynamic allocation.
Managed manually by the programmer.
Examples:
C
1 |
|
C++
1 | void func() { |
| Feature | Stack | Heap |
|---|---|---|
| Lifetime | Automatically managed | Manually managed |
| Allocation Speed | Fast | Slower |
| Memory Size | Limited (few MBs) | Much larger (system dependent) |
| Syntax in C | Just declare | malloc(), calloc(), free() |
| Syntax in C++ | Just declare | new, delete |
| Use Case | Temporary local variables | Dynamic data (e.g. arrays, objects) |
In C++: malloc()/ free() vs new/delete
My Implementation of new and delete
- Title: Reflection on C and C++ Memory Allocation Difference
- Author: Ricardo Pu
- Created at : 2025-04-20 23:04:00
- Updated at : 2025-04-21 14:10:24
- Link: https://ricardopotter.github.io/RicardoBlog/2025/04/20/Reflection-on-C-and-CPP-Memory-Allocation-Difference/
- License: This work is licensed under CC BY-NC-SA 4.0.