ProgrammingHardWipro · Cognizant pattern

What happens when this runs?

What happens when this runs?
char buf[5];
strcpy(buf, "hello world");
printf("%s", buf);
  1. A. It safely truncates to fit buf's 5 bytes
  2. B. Undefined behaviour: strcpy writes past the end of buf (a 12-byte string into a 5-byte buffer), a classic buffer overflow
  3. C. Compile-time error: the string literal is too long for buf
  4. D. It prints exactly "hello" with no issue

Correct answer: B. Undefined behaviour: strcpy writes past the end of buf (a 12-byte string into a 5-byte buffer), a classic buffer overflow

strcpy does not know or respect the destination buffer's size; it copies the source string plus its terminating '\0' unconditionally. "hello world" needs 12 bytes but buf only has 5, so this overflows the buffer, corrupting adjacent memory — undefined behaviour, and a textbook security vulnerability (use strncpy or snprintf with an explicit size instead).

More C Programming questions

Exams that ask this topic