Memory Management Concepts MCQs for the NSCT

By the NSCT Exam Editorial Team · Updated 2026-11-24 · Facts checked against official sources on 2026-11-24

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

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

Interactive quiz loading. The first 10 questions are shown below.

  1. In C++, where is a non-static local variable such as `int count = 0;` declared inside a function normally stored?

    1. On the call stack, in that function's stack frame
    2. On the heap
    3. In the text (code) segment
    4. In the static/global data segment
    Show answer

    Answer: A. On the call stack, in that function's stack frame

    Non-static local variables live in the stack frame created when the function is called and are released automatically when it returns. The heap is only used when you allocate explicitly (new/malloc); static and global variables sit in the static data segment; the text segment holds machine code.

  2. In C++, which statement correctly releases memory obtained with `int* a = new int[50];`?

    1. delete a;
    2. free(a);
    3. a = nullptr;
    4. delete[] a;
    Show answer

    Answer: D. delete[] a;

    Memory from new[] must be released with delete[], which knows to destroy every element of the array. Plain delete on an array, or free() on memory from new, is undefined behaviour, and setting the pointer to nullptr only loses the address, causing a leak.

  3. In Java, where is the object created by `new StringBuilder()` stored?

    1. On the stack of the method that created it
    2. In the CPU registers until the method ends
    3. In the class file on disk
    4. On the heap; the variable holding it stores only a reference
    Show answer

    Answer: D. On the heap; the variable holding it stores only a reference

    Every Java object is allocated on the heap. A local variable such as `StringBuilder sb` lives in the stack frame and holds a reference to that heap object. When no references remain, the garbage collector can reclaim the object.

  4. What is a memory leak?

    1. Reading memory beyond the end of an array
    2. Heap memory that the program no longer needs or can reach but never releases
    3. A variable that goes out of scope when a function returns
    4. Memory that the operating system takes back when the program exits
    Show answer

    Answer: B. Heap memory that the program no longer needs or can reach but never releases

    A leak happens when allocated memory is never freed even though the program has stopped using it, typically because the last pointer to it was lost. Leaked memory accumulates, so long-running programs can exhaust memory. Out-of-bounds reads are a different bug (buffer overrun).

  5. In C++, what is a dangling pointer?

    1. A pointer that has been set to nullptr
    2. A pointer declared but never used
    3. A pointer that still holds the address of memory that has been freed or has gone out of scope
    4. A pointer to a function rather than to data
    Show answer

    Answer: C. A pointer that still holds the address of memory that has been freed or has gone out of scope

    A dangling pointer points to memory that is no longer valid, for example after delete or after the local variable it pointed to went out of scope. Dereferencing it is undefined behaviour. A nullptr is the safe opposite: it clearly points to nothing.

  6. In Java, which error is thrown when a method calls itself recursively with no base case until the thread runs out of call-stack space?

    1. OutOfMemoryError
    2. NullPointerException
    3. ArrayIndexOutOfBoundsException
    4. StackOverflowError
    Show answer

    Answer: D. StackOverflowError

    Each call pushes a new frame on the thread's stack; unbounded recursion fills the stack and the JVM throws StackOverflowError. OutOfMemoryError is thrown when the heap (or another memory area) cannot satisfy an allocation. Both are Errors, not Exceptions.

  7. How does CPython (the standard Python interpreter) mainly decide when to free an object?

    1. The programmer must call del on every object to free it
    2. Only a mark-and-sweep collector that runs every few seconds
    3. Objects are freed when the function that created them returns, like stack variables
    4. It keeps a reference count on every object and frees it when the count reaches zero, with a cycle-detecting collector for reference cycles
    Show answer

    Answer: D. It keeps a reference count on every object and frees it when the count reaches zero, with a cycle-detecting collector for reference cycles

    CPython stores a reference count in each object; when the count falls to zero the object is deallocated immediately. Because reference counting cannot free cycles (objects that refer to each other), CPython also has a generational cyclic garbage collector in the gc module. del only removes a name, decreasing the count by one.

  8. What does RAII (Resource Acquisition Is Initialisation) mean in C++?

    1. A resource is acquired in an object's constructor and released in its destructor, so its lifetime is tied to the object's scope
    2. All resources must be initialised to zero before use
    3. Resources are allocated at compile time instead of at run time
    4. The garbage collector releases resources when memory runs low
    Show answer

    Answer: A. A resource is acquired in an object's constructor and released in its destructor, so its lifetime is tied to the object's scope

    With RAII, a stack object owns a resource (memory, a file, a lock). When the object goes out of scope, normally or because an exception is thrown, its destructor runs and releases the resource. std::vector, std::unique_ptr, std::fstream and std::lock_guard all follow this idiom.

  9. Which C++ smart pointer represents sole ownership and can be moved but not copied?

    1. std::shared_ptr
    2. std::unique_ptr
    3. std::weak_ptr
    4. A raw pointer declared const
    Show answer

    Answer: B. std::unique_ptr

    std::unique_ptr has a deleted copy constructor, so exactly one unique_ptr owns the object at a time; ownership can be transferred with std::move. shared_ptr allows many owners through a reference count, and weak_ptr is a non-owning observer of a shared_ptr.

  10. Which C++ smart pointer refers to an object managed by std::shared_ptr without increasing its strong reference count?

    1. std::unique_ptr
    2. std::auto_ptr
    3. A second std::shared_ptr
    4. std::weak_ptr
    Show answer

    Answer: D. std::weak_ptr

    weak_ptr observes a shared object without owning it, so it does not keep the object alive. You call lock() to get a temporary shared_ptr if the object still exists. This is the standard way to break shared_ptr reference cycles. auto_ptr is an old ownership pointer, removed in C++17.

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.