ProgrammingVery hard
To read a whole line of unknown length in standard C without overflow, which approach is correct?
- A. Use gets, which is safe for any length
- B. Use scanf("%s") with a fixed 10-byte buffer
- C. Read in chunks with fgets and grow a malloc'd buffer with realloc when a newline is not yet seen
- D. Use strcpy from stdin into a fixed 100-byte buffer
Correct answer: C. Read in chunks with fgets and grow a malloc'd buffer with realloc when a newline is not yet seen
fgets with a growing buffer handles arbitrary lengths safely. gets is removed from C11 and unbounded, and the fixed buffers overflow.
More C Programming questions
- A program sums the digits of 10^5 numbers with one loop per number that divides by 10. What is the total cost, about?
- A queue for BFS on a grid of 10^6 cells uses a fixed array of size 10^6 indexed by head and tail. Is this enough?
- To find the maximum over 10^5 queries of ranges in a static array, which approach is fast enough?
- A program multiplies two n x n matrices with n = 500 in int, and the product entries reach about 10^12. What is the error?
- To answer 'how many times does x appear in a sorted array' in O(log n), which pair of searches is correct?
- A bit array for flags of 10^9 items is held as one byte per item. What is the memory use, and is it fast enough in typical limits?