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?

  1. A9 bytes are written, including the terminating '\0', corrupting 1 byte outside name (undefined behavior)
  2. BIt is exactly 8 characters, so it fits in name and ABCDEFGH is printed correctly
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. In C, which of the following describes what happens when a null pointer is dereferenced (*p is read while p is NULL)?
  2. Assume a typical environment where char is 1 byte and int is 4 bytes, with int placed at addresses that are multiples of 4. Which of the following is the output when the code above is executed?
  3. uint32_t and uint8_t are 32-bit and 8-bit unsigned integer types, and the environment is little-endian. Which of the following is the output when the code above is executed?
  4. Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?
  5. Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?