ProgrammingHardTCS NQT · Infosys pattern

What is the behavior?

What is the behavior?
char buf[5];
strcpy(buf, "hello world");
printf("%s", buf);
  1. A. Guaranteed to truncate safely at 5 characters
  2. B. Compilation error detected at compile time
  3. C. Guaranteed to print exactly "hello"
  4. D. Undefined behavior: strcpy writes past the end of the 5-byte buffer (buffer overflow)

Correct answer: D. Undefined behavior: strcpy writes past the end of the 5-byte buffer (buffer overflow)

strcpy copies the source string including its null terminator with no bounds checking; "hello world\0" is 12 bytes, far more than buf's 5 bytes, so this overflows the buffer and corrupts adjacent memory — undefined behavior, often exploited as a security bug in real systems.

More C Programming questions

Exams that ask this topic