OA. free
Free
Texas Instruments Analog Electronics Core Computer Science Medium

Select the correct code snippet from the options below that properly allocates memory and...

Texas Instruments technical mcq question, verified with a worked answer. Free to practise - no sign-up.

Select the correct code snippet from the options below that properly allocates memory and frees it without leaving a dangling pointer:

Choose one option.
Show answer & explanation
Answer: A. malloc followed by free and null pointer assignment

To prevent a dangling pointer, memory must first be released using free() and then the pointer must be set to NULL. This ensures that any subsequent attempt to use the pointer will result in a predictable crash (segmentation fault) rather than undefined behavior from accessing freed memory.

Step-by-step Derivation:
Step 1: Analyze Option A: malloc allocates memory on the heap. free(ptr) releases that memory back to the system. ptr = NULL removes the address of the freed memory from the pointer variable, effectively eliminating the dangling pointer. This is the correct sequence.
Step 2: Analyze Option B: free(ptr) is called, but ptr still holds the memory address. This is a 'dangling pointer'. If the program attempts to dereference ptr later, it leads to undefined behavior.
Step 3: Analyze Option C: ptr = NULL is called before free(ptr). This causes a memory leak because the address of the allocated block is lost before it can be freed.
Step 4: Analyze Option D: This snippet contains a syntax error (redeclaration of int *ptr in the same scope) and fails to properly manage the first allocation's lifecycle before the second attempt, making it invalid C code.