ProgrammingVery hard

To read a whole line of unknown length in standard C without overflow, which approach is correct?

  1. A. Use gets, which is safe for any length
  2. B. Use scanf("%s") with a fixed 10-byte buffer
  3. C. Read in chunks with fgets and grow a malloc'd buffer with realloc when a newline is not yet seen
  4. 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

Exams that ask this topic