0
0
Compiler Designknowledge~20 mins

Garbage collection basics in Compiler Design - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Garbage Collection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Output of reference counting example
Consider a simple reference counting garbage collector. If an object has 0 references, it is collected. Given the following sequence:

1. Create object A
2. Create object B referencing A
3. Remove reference from B to A
4. Remove all references to B

How many objects remain after step 4?
A1 object remains (A)
B2 objects remain (A and B)
C1 object remains (B)
D0 objects remain
Attempts:
2 left
💡 Hint
Think about how reference counts change when references are removed.
🧠 Conceptual
intermediate
1:30remaining
Understanding mark-and-sweep phases
In a mark-and-sweep garbage collector, what is the main purpose of the 'mark' phase?
ATo free all objects immediately
BTo identify all objects that are still reachable
CTo compact memory by moving objects
DTo count references to each object
Attempts:
2 left
💡 Hint
Think about what the collector needs to know before freeing memory.
📋 Factual
advanced
2:00remaining
Identify error in pseudo-code for reference counting
Given this pseudo-code for decrementing reference count:

``` function decrement_ref(obj): obj.ref_count -= 1 if obj.ref_count == 0 free(obj) ```

What is the main problem with this code?
Compiler Design
function decrement_ref(obj):
  obj.ref_count -= 1
  if obj.ref_count == 0
    free(obj)
Afree(obj) should be called before decrementing ref_count
BShould check if ref_count < 0 instead of == 0
CMissing colon after if statement causes syntax error
DNo problem, code is correct
Attempts:
2 left
💡 Hint
Look carefully at the syntax of the if statement.
optimization
advanced
2:00remaining
Choosing a garbage collection strategy for cyclic references
Which garbage collection method can handle cyclic references without leaking memory?
AMark-and-sweep
BReference counting only
CManual memory management
DStack allocation
Attempts:
2 left
💡 Hint
Think about which method can detect unreachable cycles.
🔍 Analysis
expert
2:30remaining
Debugging memory leak in reference counting
A program uses reference counting but has a memory leak. Which of these scenarios is the most likely cause?
AObjects form a cycle, keeping reference counts above zero
BReference counts are decremented twice accidentally
CObjects are freed too early causing crashes
DGarbage collector runs too frequently
Attempts:
2 left
💡 Hint
Think about what reference counting cannot detect.