QUESTION 57 The statements given below depicts the scenario of which one of the given options?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
QUESTION 57
The statements given below depicts the scenario of which one of the given options?
int *a = (int *) malloc(sizeof(int));
A = NULL;
Show answer & explanation
The code allocates memory dynamically using malloc() but then immediately overwrites the pointer a with NULL without freeing the allocated memory first. This causes a memory leak because the dynamically allocated block becomes inaccessible and cannot be freed. A dangling pointer occurs when a pointer references freed memory (not the case here), and void pointers are untyped pointers (not relevant). The code compiles without errors.
Step-by-step Derivation:
Step-by-step analysis:
int *a = (int *) malloc(sizeof(int));— Allocates 4 bytes on the heap and stores the address in pointera.a = NULL;— Overwrites the pointer with NULL, losing the only reference to the allocated memory.- Result: The 4-byte block on the heap is now orphaned and cannot be accessed or freed, causing a memory leak.
Note: A dangling pointer would occur if we freed the memory and then dereferenced a. A void pointer is simply an untyped pointer, not a memory error. The code compiles successfully.