Cambo Freelance
HomeServicesArticlesTutorialsTeamCoursesContact
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

Send us a message

Ready to start your project? Get in touch with our team.

Contact Us

Services

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

Useful Links

  • Home
  • Services
  • Learning
  • About Us
  • Contact
  • Pricing

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsC++C++ Memory Management
⚡C++ Tutorials

50 lessons

Beginner(21)1C++ Introduction2C++ Getting Started3C++ Syntax4C++ Output5C++ Comments6C++ Variables7C++ Data Types8C++ Constants9C++ User Input10C++ Operators11C++ Strings12C++ Math13C++ Booleans14C++ Conditions15C++ Switch16C++ Loops17C++ Break and Continue18C++ Arrays19C++ Functions20C++ References21C++ Pointers
Intermediate(19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers
Advanced(10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44
⚡

C++ Tutorials

Lesson 47 of 50

All lessons
Beginner (21)1C++ Introduction2C++ Getting Started
26
C++ Encapsulation
27C++ Inheritance
28C++ Polymorphism
29C++ Abstraction
30C++ Files
31C++ Exception Handling
32C++ Namespaces
33C++ Structures
34C++ Enumerations
35C++ STL Introduction
36C++ Vectors
37C++ Maps
38C++ Sets
39C++ Queues
40C++ Stacks
C++ Move Semantics
45C++ Multithreading
46C++ Design Patterns
47C++ Memory Management
48C++17 Features
49C++20 Features
50C++ Performance Optimization
3
C++ Syntax
4C++ Output
5C++ Comments
6C++ Variables
7C++ Data Types
8C++ Constants
9C++ User Input
10C++ Operators
11C++ Strings
12C++ Math
13C++ Booleans
14C++ Conditions
15C++ Switch
16C++ Loops
17C++ Break and Continue
18C++ Arrays
19C++ Functions
20C++ References
21C++ Pointers
Intermediate (19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers26C++ Encapsulation27C++ Inheritance28C++ Polymorphism29C++ Abstraction30C++ Files31C++ Exception Handling32C++ Namespaces33C++ Structures34C++ Enumerations35C++ STL Introduction36C++ Vectors37C++ Maps38C++ Sets39C++ Queues40C++ Stacks
Advanced (10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44C++ Move Semantics45C++ Multithreading46C++ Design Patterns47C++ Memory Management48C++17 Features49C++20 Features50C++ Performance Optimization
⚡C++AdvancedLesson 47 of 50CamboFreelanceJune 19, 2026

C++ Memory Management

Deep dive into C++ memory management: stack vs heap, new/delete, RAII pattern, detecting memory leaks with modern tools.


Tutorials › C++ › Memory Management
Advanced11 min readLesson 47 of 50

Stack vs Heap

FeatureStackHeap
AllocationAutomaticManual (new/delete) or smart pointers
SpeedVery fastSlower
SizeLimited (~1–8 MB)Large (limited by RAM)
LifetimeScope-boundUntil freed
#include <iostream>
using namespace std;

int main() {
    // Stack allocation — automatic
    int stackVar = 42;

    // Heap allocation — manual
    int* heapVar = new int(42);
    cout << *heapVar << endl;
    delete heapVar;   // must free!
    heapVar = nullptr;

    // Heap array
    int* arr = new int[10];
    for (int i = 0; i < 10; i++) arr[i] = i * 2;
    delete[] arr;   // use delete[] for arrays!
    return 0;
}

RAII — Resource Acquisition Is Initialization

The best memory management pattern: acquire resources in constructors, release in destructors. Smart pointers implement RAII automatically.

class FileHandle {
  private:
    FILE* file;
  public:
    FileHandle(const char* path) { file = fopen(path, "r"); }
    ~FileHandle()                { if (file) fclose(file); }  // auto-close!
    FILE* get()                  { return file; }
};

Detecting Memory Leaks

// Leak — every new needs a matching delete
int* p = new int(5);
// forgot: delete p;  <-- leak!

// Fix: use smart pointers
auto p = make_unique<int>(5);
// auto-freed when p goes out of scope

Tools: Valgrind (Linux/macOS), AddressSanitizer (-fsanitize=address), Visual Studio Diagnostic Tools.

Exercise

Implement a RAII class MemoryBlock that allocates a dynamic array of N ints in its constructor and frees it in its destructor. Use it to store and print 5 values.

Show Solution
#include <iostream>
using namespace std;

class MemoryBlock {
  private:
    int* data;
    int  size;
  public:
    MemoryBlock(int n) : size(n), data(new int[n]) { cout << "Allocated\n"; }
    ~MemoryBlock() { delete[] data; cout << "Freed\n"; }
    int& operator[](int i) { return data[i]; }
    int  getSize() { return size; }
};

int main() {
    MemoryBlock block(5);
    for (int i = 0; i < block.getSize(); i++) block[i] = i * 10;
    for (int i = 0; i < block.getSize(); i++) cout << block[i] << " ";
    cout << endl;
    return 0;
}

Quiz

  1. What keyword deallocates a heap array?

    • A) delete ptr
    • B> free(ptr)
    • C) delete[] ptr
    • D> remove(ptr)
    Answer

    C) delete[] — use delete[] for arrays allocated with new[].

Summary

  • Stack is fast and automatic; heap is flexible but must be managed.
  • Always pair new with delete, and new[] with delete[].
  • RAII wraps resources in objects with constructors/destructors.
  • Prefer smart pointers to eliminate memory leaks entirely.
← Previous: Design Patterns Next: C++17 Features →
c++memory-managementraiiadvanced
PreviousLesson 46: C++ Design PatternsNextLesson 48: C++17 Features
Back to All Tutorials