What is the memory overhead when allocating 1000 integers vs 1 integer in a system with malloc metadata?
ANegligible difference
BProportional to number of allocations
CFixed overhead per allocation regardless of size
DExponential with allocation count
Correct Answer:
C. Fixed overhead per allocation regardless of size
EXPLANATION
Each malloc() call has fixed metadata overhead (typically 8-16 bytes). Single allocation of 1000 ints has less overhead than 1000 separate allocations.
Correct Answer:
A. int *arr = (int*)malloc(n * sizeof(int)); if(!arr) return -1;
EXPLANATION
Checking if malloc returns NULL before using the pointer is essential error handling. If allocation fails, the program should handle it gracefully rather than proceeding with NULL.
In a dynamic stack implementation for competitive programming, how should you handle reallocation when the stack becomes full?
AUse realloc() to double the capacity and copy old data
BReturn an error and stop accepting elements
CAllocate a new stack dynamically
DUse a fixed-size array instead
Correct Answer:
A. Use realloc() to double the capacity and copy old data
EXPLANATION
Doubling capacity and using realloc() provides amortized O(1) insertion with manageable memory overhead, which is the standard approach for dynamic data structures.