CPP Memory Management & Performance Optimization 2 — Questions and Answers
Question 1: What is a dangling pointer?
- A pointer that points to freed or invalid memory (Correct answer)
- A pointer that has never been initialized
- A pointer used in a loop
- A pointer to a function
Correct answer: A pointer that points to freed or invalid memory
A dangling pointer references memory that has already been freed, leading to undefined behavior if dereferenced.
Question 2: Which profiling technique samples the call stack at regular intervals to identify hotspots?
- Instrumentation profiling
- Sampling profiling (Correct answer)
- Heap profiling
- Branch profiling
Correct answer: Sampling profiling
Sampling profilers periodically capture the call stack to approximate where a program spends most of its time with low overhead.
Question 3: What is the purpose of lazy initialization?
- Initialize all objects at application startup
- Defer object creation until the first time it is actually needed (Correct answer)
- Initialize objects in a background thread
- Use default constructors exclusively
Correct answer: Defer object creation until the first time it is actually needed
Lazy initialization avoids expensive setup until it's necessary, improving startup time and avoiding unnecessary resource use.
Question 4: What causes a stack overflow error?
- Allocating too many objects on the heap
- Excessive recursion or very large local variables exhausting the call stack (Correct answer)
- Writing past the end of an array on the heap
- Using too many threads simultaneously
Correct answer: Excessive recursion or very large local variables exhausting the call stack
A stack overflow occurs when the call stack grows beyond its fixed size limit, typically due to infinite or very deep recursion.
Question 5: What is memory fragmentation and how does it affect performance?
- Splitting data across multiple files
- Free memory blocks scattered throughout the heap making it hard to allocate large contiguous blocks (Correct answer)
- Using too many threads
- Storing variables in the wrong data type
Correct answer: Free memory blocks scattered throughout the heap making it hard to allocate large contiguous blocks
Heap fragmentation results in wasted memory and allocation failures even when total free memory is sufficient but not contiguous.
Question 6: What is memoization in the context of performance optimization?
- Storing program state to disk for crash recovery
- Caching the results of expensive function calls and returning the cached result for the same inputs (Correct answer)
- Pre-allocating memory at application start
- Profiling memory usage at runtime
Correct answer: Caching the results of expensive function calls and returning the cached result for the same inputs
Memoization avoids redundant computation by storing previously computed results, trading memory for speed.
What is a dangling pointer?