C++ Beginner · Lesson 11 of 22
Memory model: stack vs heap, new/delete, and why raw pointers are dangerous
Where objects live, manual allocation, leaks and dangling pointers.
Estimated time · 60–90 min
Learning goals
What you will understand
- Explain memory model: stack vs heap, new/delete, and why raw pointers are dangerous in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
Local variables live on the stack and are destroyed automatically when the scope ends. Objects created with new live on the heap until you delete them. Forgetting delete leaks memory; deleting twice or using the object after delete is undefined behaviour.
Raw owning pointers are dangerous because the type does not say who must delete the object, and any early return or exception skips the delete. Modern C++ therefore avoids new and delete in application code and uses RAII and smart pointers instead.
Guided lesson
Work through these steps
- 1.
Read the memory model: stack vs heap, new/delete, and why raw pointers are dangerous example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
int on_stack{5};
// Lives on the stack; freed automatically at the closing brace.
int* on_heap = new int{5};
// Allocates an int on the heap and returns its address; you now own it.
std::cout << *on_heap << '\n';
// Read through the pointer.
delete on_heap;
// Release the memory; the pointer now dangles.
on_heap = nullptr;
// Clear the pointer so it cannot be used by mistake.
double* buffer = new double[100];
// Allocates an array of 100 doubles on the heap.
delete[] buffer;
// Arrays need delete[]; plain delete on an array is undefined behaviour.
// std::vector<double> better(100);
// The safe alternative: memory is freed automatically.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Memory model: stack vs heap, new/delete, and why raw pointers are dangerous. Expected result: sum 30
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
int main() {
// TODO: allocate an array of 3 ints on the heap with new[], fill it with i * 10, add them up, then delete[] it
std::cout << "sum " << sum << '\n';
return 0;
}Expected output
sum 30Stuck? Show the full solution (try it yourself first)
#include <iostream>
int main() {
int* values = new int[3];
int sum{0};
for (int i = 0; i < 3; ++i) {
values[i] = i * 10;
sum += values[i];
}
delete[] values;
std::cout << "sum " << sum << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Write a function that allocates with new and returns early on an error path without deleting. Run it under g++ -fsanitize=address to see the leak report, then rewrite it with std::vector so the leak disappears.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.