Memory Management & Pointers Flashcards
7 cards from real CPP practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Memory Management & Pointers flashcards as text
What is the role of std::weak_ptr in C++?
Answer: To provide a non-owning reference that does not affect the reference count of a shared_ptr
std::weak_ptr holds a non-owning reference to an object managed by shared_ptr without incrementing the reference count, helping break circular references.
What is the difference between stack and heap memory in C++?
Answer: Stack memory is automatically managed and limited in size; heap memory is manually managed and larger
Stack memory is automatically managed by the compiler with a limited size, while heap memory is manually allocated/deallocated and can be much larger.
Which scenario is most likely to cause a memory leak in C++?
Answer: Allocating memory with new inside a function and returning without calling delete
Allocating heap memory with new and not calling delete before the pointer goes out of scope causes a memory leak.
What does new[] allocate and how must it be freed?
Answer: An array of objects; freed with delete[]
new[] allocates an array of objects and must be freed with delete[] to ensure all destructors are called and memory is properly released.
What is the output of: int arr[3] = {10,20,30}; int* p = arr; std::cout << *(p+2);
Answer: 30
p+2 advances the pointer by 2 integer positions, pointing to the third element (30), and dereferencing it yields 30.
What does the RAII idiom guarantee in C++ memory management?
Answer: Resources are acquired in a constructor and released in the corresponding destructor
RAII (Resource Acquisition Is Initialization) ensures that resources are tied to object lifetimes, with acquisition in the constructor and release in the destructor.
In C++, what is a void pointer (void*)?
Answer: A generic pointer that can hold the address of any data type but must be cast before dereferencing
A void* can store the address of any type but cannot be dereferenced directly; it must be cast to the appropriate type first.