MCQ Hive stays free thanks to ads. Please disable your ad blocker for this site so content and features keep working.
Fundamental Programming
Memory Management
Beginner
Q
What is wrong with this C++ function?
int* f(){ int x = 5; return &x; }
AMemory leak
BCompilation error
CNothing; it works correctly
DIt returns a dangling pointer to a local variable that no longer exists
Correct Answer:
D. It returns a dangling pointer to a local variable that no longer exists
Explanation:
x is destroyed when f returns. Dereferencing the returned pointer is undefined behavior.
ALSO KNOW (related points):
• How does CPython primarily manage memory? → Reference counting, plus a cyclic garbage collector
• Given int arr[5]; int *p = arr; with 4-byte ints, how many bytes does p + 2 advance from arr? → 8 bytes
• What does C's malloc return when the requested memory cannot be allocated? → NULL