Every object your program creates lives in one of two places, and knowing which is the difference between code that works and code that works by accident.
The stack is a region the compiler manages for you. Every local variable and every function parameter goes there. It is fast - allocation is moving a pointer - and it is automatic: when a function returns, its whole frame is discarded and the destructors of everything in it run. It is also small, typically one to eight megabytes, and the size of each object must be known at compile time. Returning the address of a stack variable is a classic bug: the memory it names stops being yours the moment the function returns.
The heap is memory you request at runtime and are responsible for. It is large - as large as the machine will give you - the size can be decided while running, and the lifetime is whatever you choose. The cost is that nothing frees it for you. Allocate with new and never delete, and you have a memory leak. delete twice and you have corruption. delete and then use the pointer and you have a dangling pointer, which is undefined behaviour and may not crash for hours.
A pointer is a variable holding a memory address. int* p = &x; stores the address of x; *p dereferences it, reading or writing what is at that address. A pointer with no target should be nullptr - not NULL and not 0, both of which are integers wearing a disguise and can pick the wrong overload. Pointer arithmetic moves in units of the pointed-to type: p + 1 on an int* advances four bytes, not one, which is exactly how array indexing works underneath.
A reference is an alias for an existing object: int& r = x; makes r another name for x. It must be initialized, it can never be rebound to something else, and it cannot be null. That is why a reference is the default choice for a function parameter - it gives you the efficiency of not copying with none of the ways a pointer can go wrong. Pass const T& when you only need to read, which is most of the time. Pass T& when you intend to modify the caller's object. Pass by value only for small, cheap types like int.
Everything in this topic is the mechanism. Phase 3 replaces almost all of it with smart pointers, and you should use those in real code. Learn this first anyway: a unique_ptr is a thin shell over exactly these operations, and you cannot debug what you do not understand.
#include <iostream>
#include <string>
// --- Pass by value: the function gets a copy. ---
void by_value(int n) { n = 99; } // caller unaffected
// --- Pass by reference: an alias for the caller's object. ---
void by_reference(int& n) { n = 99; } // caller's int changes
// --- Pass by const reference: no copy, and cannot modify. ---
void read_only(const std::string& s)
{
std::cout << s.size() << '\n';
// s += "x"; // ERROR, which is the point of const
}
// --- Pass by pointer: can be null, and the caller sees that it may be. ---
void by_pointer(int* n)
{
if (n == nullptr) { return; } // a reference could not be null here
*n = 99;
}
int main()
{
// --- The stack ---
int x{10};
int& r = x; // r IS x. Not a copy, not a pointer.
r = 20;
std::cout << x << '\n'; // 20
// int& bad; // ERROR: a reference must be initialized
// r = other; // this assigns to x; it does NOT rebind r
// --- Pointers ---
int* p = &x; // p holds the address of x
std::cout << p << '\n'; // the address itself, e.g. 0x7ffd...
std::cout << *p << '\n'; // 20 - dereference to read through it
*p = 30; // write through it
std::cout << x << '\n'; // 30
int* nothing = nullptr; // nullptr, not NULL and not 0
// std::cout << *nothing; // UB. Dereferencing null.
// --- Pointer arithmetic moves in units of the type ---
int arr[4]{10, 20, 30, 40};
int* a = arr; // arrays decay to a pointer to arr[0]
std::cout << *(a + 2) << '\n'; // 30 - and this IS what arr[2] means
std::cout << a[2] << '\n'; // 30 - identical
// --- The heap ---
int* heap_int = new int{42}; // one int, on the heap
int* heap_arr = new int[1000]{}; // a thousand, zero-initialized
std::cout << *heap_int << '\n';
delete heap_int; // delete pairs with new
delete[] heap_arr; // delete[] pairs with new[]. Not interchangeable.
heap_int = nullptr; // so a later use fails loudly rather than quietly
heap_arr = nullptr;
// --- The three ways heap memory goes wrong ---
//
// int* leak = new int{1}; // never deleted -> leak
//
// int* twice = new int{1};
// delete twice; delete twice; // deleted twice -> corruption
//
// int* dangling = new int{1};
// delete dangling;
// *dangling = 2; // used after delete -> UB
//
// Phase 3 removes all three by removing the delete. Until then,
// build with the sanitiser and it will tell you:
//
// g++ -std=c++20 -fsanitize=address,undefined -g main.cpp -o main
by_value(x); std::cout << x << '\n'; // 30 - unchanged
by_reference(x); std::cout << x << '\n'; // 99
by_pointer(&x);
read_only("a string literal binds to const& without a copy");
return 0;
}
Discussion
No questions on this topic yet. Sign in to ask the first one.