C++ Review Flashcards
Memory
C++ program has two key areas: Stack and Heap
Stack
- Manages function calls and control flow, stores local variables, function parameters as local variables, and return addresses
- Each function call creates a stack frame
- Limited in Size
- LIFO (Last-In-First-Out)
- Automatically managed by system
- Everything is destroyed when goes out of scope
Heap
- Enables dynamic allocation; a.k.a., allocating memory on heap during runtime
- Larger size
- new keyword to perform allocation
- delete keyword to free memory/prevent leaks
Pointers
- Store memory addresses
- Dereferencing to access data at the address
- Ensure type safety
- Pointer Arithmetic to navigate arrays
Dynamic allocation
- Allows memory allocation at runtime
- Helpful for large or unknown data sizes
- e.g.
size_t array_size; std::cout << "array size: "; std::cin >> array_size; int* array_ptr = new int [array_size] {10}; delete[] array_ptr;
Memory Errors
Crucial to for avoid program crashes, data corruption and security vulnerabilities
Stack overflow
Exceeding stack size, often by recursion or large arrays
Index out of bounds
Accessing an area in memory outside an array’s scope
Memory leak
Deleting the reference to your data on the heap so the data is no longer accessible; leading to wasted memory resources and unexpected behavior
Dangling pointers
Pointer that points to an address that was previously de-allocated. To avoid this, always set the pointer to nullptr after freeing the memory using delete;
~~~
delete age_ptr;
age_ptr = nullptr;
~~~
Use After Free
Trying to access memory after it’s been de-allocated
Double Free
double deletion on the same pointer; aka trying to free memory twice
Uninitialized memory access / Segementation Fault
int * pointer; std::cout << *pointer << std::endl;
Operator Overloading
Enabling user-defined objects to work with standard operators; e.g., ==, =, >, <, «,»_space;
Constructors
Initialize objects. If overloaded, you can create objects under different scenarios based on the parameters
“Big 3”
For any class, you should have the Copy Constructor, Destructor, and Copy Assignment Operator
Template Functions
- Function blueprint with generic data types
- Compiler generates the actual functions for needed data types based on how the functions are called at compile time!
- Must specify data type in angle brackets
- Following example works for chars, doubles, ints
- `template <typename>
T max(T a, T b)
{
return (a>b) ? a : b;
}</typename>in main:int x = 5;
int y = 2;max <int> (x,y);
`</int>
Stack Frame
- Created and pushed onto stack during function call
*
Template Classes
template <typename></typename>