Memory Management Concepts MCQs for the NSCT
Memory management is how a program gets memory for its data and gives it back: the stack for function calls, the heap for objects, and either manual freeing (C++) or automatic garbage collection (Java, Python). It is the tenth of 16 topics in the Programming (C++/Java/Python) area, which carries 10% of the NSCT according to HEC's Areas of Competencies.
Expect questions on where a variable lives, what a pointer or reference points to, when an object can be freed, and what goes wrong with leaks and dangling pointers. It builds on functions and methods, because every call creates a stack frame.
Stack vs heap
The stack holds one frame per active function call, containing its parameters and local variables. Frames are pushed on call and popped on return, so stack memory is freed automatically. The heap holds memory you request at run time (new in C++ and Java, every object in Python), and it lives until it is freed or collected.
| Stack | Heap | |
|---|---|---|
| Holds | Call frames, local variables | Dynamically allocated objects |
| Freed | Automatically on return | delete (C++) or garbage collector |
| Speed | Very fast (move a pointer) | Slower (allocator bookkeeping) |
| Size | Small, fixed per thread | Large, grows as needed |
| Failure | Stack overflow (deep recursion) | Out of memory, fragmentation |
In Java, StringBuilder sb = new StringBuilder(); puts the object on the heap and the reference sb in the stack frame.
Exam angle: StackOverflowError points to runaway recursion; OutOfMemoryError points to the heap.
Pointers and references
A pointer (C++) is a variable that stores an address. *p dereferences it, and p + 1 moves by one element, not one byte. A C++ reference is an alias: it must be bound when declared, cannot be null and cannot be re-bound.
int x = 10;
int* p = &x; // p holds x's address
int& r = x; // r is another name for x
*p = 20; // x is now 20, and so is r
Java and Python have no pointer arithmetic. Their variables hold references to heap objects, so b = a makes two names for one object. In Python, a is b tests that identity, while a == b compares values.
Exam angle: returning &local from a C++ function leaves a dangling pointer, because the frame is gone. See pointers and memory for longer pointer traces.
Manual memory and RAII in C++
Memory from new must be released with delete, and memory from new[] with delete[]. Mismatching them, deleting twice, or using memory after delete is undefined behaviour. Forgetting to delete is a memory leak.
RAII (Resource Acquisition Is Initialisation) ties a resource to an object's lifetime: the constructor acquires it and the destructor releases it, even if an exception is thrown. Smart pointers apply RAII to heap memory:
| Smart pointer | Ownership |
|---|---|
std::unique_ptr |
One owner; movable, not copyable |
std::shared_ptr |
Shared; freed when the use count reaches 0 |
std::weak_ptr |
Observes a shared_ptr without owning it; breaks cycles |
Exam angle: two shared_ptr objects that point at each other never reach a count of 0, so they leak. The fix is to make one link a weak_ptr.
Garbage collection and reference counting
A garbage collector frees heap objects that the program can no longer reach. Java uses tracing collectors: starting from GC roots (thread stacks, static fields), mark what is reachable and reclaim the rest. Most JVM collectors are generational, because most objects die young. System.gc() is only a request.
CPython mainly uses reference counting: each object counts the references to it and is freed the moment the count hits 0. A separate cycle detector (the gc module) handles objects that refer to each other.
import sys
x = []
before = sys.getrefcount(x)
y = x # +1
z = [x, x] # +2
print(sys.getrefcount(x) - before) # 3
Exam angle: in Java, two objects that only point to each other are still eligible for collection, because tracing works on reachability, not counts.
Common traps
- Thinking
del ain Python deletes the object. It removes one name, and the object survives while other references exist. - Saying an object is eligible for GC as soon as one variable is set to
null, even though another reference still exists. - Using
deleteon memory fromnew[], orfree()on memory fromnew. - Assuming garbage collection prevents all leaks. A static list that keeps growing in Java is still a leak.
- Mixing up
StackOverflowError(stack) andOutOfMemoryError(heap). - Treating a C++ reference like a pointer that can be null or re-pointed.
Worked examples
1. Understanding. Which C++ smart pointer gives sole ownership and cannot be copied?
Answer: std::unique_ptr. Its copy constructor is deleted; ownership moves with std::move.
2. Application. In Java, Box p = new Box(); Box q = new Box(); p = q; runs. How many Box objects are eligible for garbage collection?
Answer: 1. The first Box lost its only reference when p was reassigned; the second is still reachable through both p and q.
3. Analysis. A C++ function allocates int* buf = new int[n];, calls a function that may throw, then calls delete[] buf;. What is the risk?
Answer: if the call throws, delete[] is skipped and the array leaks. Using std::vector<int> buf(n); frees it on every exit path.
Practise
The quiz below has 100 questions on this topic, filterable by tier and difficulty.
Practise: 100 questions
FAQs
Is Python's memory on the stack or the heap?
Every Python object, even a small int, lives on a private heap managed by the interpreter. Function calls still use frames, but a frame's local variables are names holding references to heap objects. That is why assigning a list to a new name never copies it; you need list(a), a[:] or copy.copy.
Does Java have pointers?
Java has references, which behave like pointers you cannot do arithmetic on. You cannot take the address of a variable or free memory yourself; the garbage collector reclaims unreachable objects. A null reference used with a dot gives NullPointerException, Java's version of dereferencing a null pointer.
What is the difference between a memory leak and a dangling pointer?
A leak frees memory too late (never): the program loses its last reference without releasing the block. A dangling pointer is the opposite problem: memory is freed too early while a pointer still refers to it. Leaks waste memory gradually; dangling pointers cause undefined behaviour and crashes.
Can garbage-collected languages still run out of memory?
Yes. A collector can free only unreachable objects. If your code keeps references alive, for example in a growing cache, a static collection or a listener list, memory keeps rising until OutOfMemoryError or MemoryError. Very deep recursion also exhausts the stack regardless of the collector.
Next step
Move on to Exception & Error Handling MCQs, see all topics on the Programming MCQs hub, or test yourself in an NSCT mock test.