Memory Management
- Memory stores programs; i.e., instructions and data
- The Operating System and the C++ runtime manages memory
Quiz: What is a variable?
A pair of a name with its semantics and a corresponding location for storage, normally memory
Quiz: What is a pointer?
A variable that stores a memory address
Parts of a Program in Memory
Text and Operating System parts
- Operating System: The operating system restricts some memory area for itself
- Text: Portion of memory storing the code of our program; e.g.,
main
function
Data, Heap, and Stack
- Data: Area storing global variables with lifetime equal to the program
- Heap: Area storing variables dynamically allocated, unknown lifetime and not function limited
- Stack: Area storing variables created within the scope of a function
Heap and Stack example
source: https://courses.grainger.illinois.edu/cs225/fa2022/resources/stack-heap/
Quiz: Pointers' storage
Can the heap, stack and data sections store pointers?
Quiz: What is the output of this code?
C++ parameters default pass
In C++, pass-by-copy is the default policy
Quiz: What is the output of this code?
Pointers to the rescue
Pointers can be dangerous
nullptr, the pointer literal
nullptr
represents the null pointer constant
- Its type is
std::nullptr_t
can be converted to any pointer type
- Never use
NULL
or 0
for pointers
NULL bad use example
source: https://learn.microsoft.com/es-es/cpp/cpp/nullptr?view=msvc-170
References
- An alias to an already-existing object or function
- Access to references are the same to the object they point to
Pointers and Arrays
Arrays
- Definition:
int array[3]={0, 1, 2};
- Normally, they will be allocated in the stack
Dynamic Memory Allocation
Pointer Arithmetic
a[i] == *(a + i * sizeof(a[0]))