safe realloc in C: solved exercise
safe realloc in C: solved exercise
This exercise is scheduled for daily publication and follows the standard site structure: statement, solution, and expected output.
Problem statement
Resize a dynamic array and avoid memory loss when realloc fails.
C solution
Expected output
Common mistakes
- Assigning
reallocdirectly to the original pointer and losing the reference if it fails. - Not freeing memory on error paths.
- Resizing without correctly updating the number of elements.
Practical use
Using realloc with a temporary variable is the safe pattern for resizing dynamic buffers without leaks on failure.
Recommended next exercise
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.