Core Module
12 min forge

C++ Memory Pointers

Advanced pointers, memory addresses, and arithmetic.

C++ Memory Pointers

πŸ“˜ What is it

Pointers are variables that store memory addresses. In memory management, pointers are the primary way to interact with the heap. They allow for manual control over memory, which is a key feature of C++.

⚑ When to use

Use pointers for dynamic resource management, building custom data structures (Lists, Trees), and passing large objects efficiently.

🧠 Time complexity

  • Access/Dereference: $O(1)$
  • Arithmetic: $O(1)$

πŸ’» Code example

cpp Standard
int x = 10; int *p = &x; // x's address std::cout << *p; // 10 *p = 20; // x becomes 20

❌ Common mistakes

  • Wild Pointers: Pointers that are not initialized to anything (not even nullptr).
  • Memory Leaks: Losing the address of heap-allocated memory before freeing it.
  • Arithmetic Errors: Incrementing a pointer by 1 moves it by sizeof(type) bytes, not necessarily 1 byte.