Assuming missing free causes crash or wrong output
Confusing memory leak with runtime errors
Expecting zero or garbage output
4. Identify the problem in this C code snippet:
char *str = malloc(20);
strcpy(str, "Hello World");
// No free(str) called
str = malloc(30);
strcpy(str, "New String");
free(str);
medium
A. No problem, code is correct
B. Syntax error in strcpy usage
C. Double free error
D. Memory leak due to first malloc not freed
Solution
Step 1: Trace memory allocations
First malloc(20) is assigned to str, then overwritten by second malloc(30).
Step 2: Check freeing of memory
First allocated memory is lost without free, causing memory leak.
Final Answer:
Memory leak due to first malloc not freed -> Option D
Quick Check:
Overwriting pointer without free causes leak [OK]
Hint: Always free old memory before reassigning pointer [OK]
Common Mistakes:
Thinking strcpy causes syntax error
Assuming double free without repeated free calls
Believing code is leak-free because free is called once
5. You have a function that allocates memory for an integer array and returns it. Which practice helps prevent memory leaks when using this function multiple times?
hard
A. Use global variables to store allocated memory
B. Never call free() because the function handles it internally
C. Always call free() on the returned pointer before reassigning it
D. Allocate memory only once and never reuse pointers
Solution
Step 1: Understand ownership of allocated memory
The caller owns the memory returned and must free it to avoid leaks.
Step 2: Prevent leaks by freeing before reassignment
Calling free() before reassigning pointer prevents losing track of allocated memory.
Final Answer:
Always call free() on the returned pointer before reassigning it -> Option C
Quick Check:
Free before reuse prevents leaks [OK]
Hint: Free returned memory before pointer reuse [OK]
Common Mistakes:
Assuming function frees memory automatically
Using global variables without freeing
Avoiding reuse but causing inefficient memory use
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.