C Programming Basics
void save(const char *input) {
char name[8];
strcpy(name, input);
printf("%s\n", name);
}The 8-character string "ABCDEFGH" was passed to the function save above. Which of the following is what happens?
- A9 bytes are written, including the terminating '\0', corrupting 1 byte outside name (undefined behavior)
- BIt is exactly 8 characters, so it fits in name and ABCDEFGH is printed correctly
- Cstrcpy truncates to 7 characters to fit the size of name and puts the terminating '\0' in the last element
Show answer and explanation
Answer: A. 9 bytes are written, including the terminating '\0', corrupting 1 byte outside name (undefined behavior)
The string "ABCDEFGH" is 9 bytes including the terminating '\0'. strcpy does not know the size of the destination and copies everything up to '\0', so it writes 1 byte past the end of the 8-byte name (a buffer overflow). The excess can corrupt other variables on the stack or the return address, and it is also exploited by attacks that supply long input to run arbitrary code. It is prevented by using a function that takes the size to write, as in snprintf(name, sizeof name, "%s", input).
- A. Correct. The 9th byte, '\0', is written outside the array.
- B. An 8-character string needs 9 bytes including the terminating '\0'.
- C. strcpy does not know the size of the destination, so it does not truncate.