65.9k views
4 votes
What happens when a string longer than the size of the array is entered using `fgets()` in C?

a) String is truncated to fit the array size
b) Program crashes with a segmentation fault
c) Compiler throws a warning message
d) String overwrites adjacent memory

User Meg Risdal
by
8.4k points

1 Answer

2 votes

Final answer:

Using fgets() in C, if a string longer than the array is entered, the string is truncated to fit the array size, with fgets() designed to avoid buffer overflow issues.

Step-by-step explanation:

When using fgets() in C, if a string longer than the size of the array is entered, the correct behavior is that the string is truncated to fit the array size. The function is designed to read up to one less than the number of characters specified by the array size from a given input stream into the buffer pointed to by the string. This includes a null-terminator, so if the array size is 10, fgets() will read at most 9 characters and then add a null-terminator as the 10th character.

If the input is longer than the buffer, fgets() will store the number of characters that fit into the buffer and discard the rest, effectively truncating the string. It will not cause a program crash or overwrite adjacent memory. Such buffer overflows can be a source of bugs and security issues, but fgets() is designed to help avoid these by limiting the number of characters read.

User Schnatterer
by
7.8k points