ProgrammingHardTCS NQT · Infosys pattern
What is the behavior?
What is the behavior?
char buf[5];
strcpy(buf, "hello world");
printf("%s", buf);- A. Guaranteed to truncate safely at 5 characters
- B. Compilation error detected at compile time
- C. Guaranteed to print exactly "hello"
- 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
- What is the behavior? c int a = 10; int b = a << 32; printf("%d", b);
- What is the behavior? c const int x = 10; int p = (int)&x; p = 20; printf("%d", x);
- What is the behavior? c int a[3] = {1, 2, 3}; memcpy(a, a + 1, 2 sizeof(int)); printf("%d %d %d", a[0], a[1], a[2]);
- What is the behavior? c void f(int n) { char buf[n]; for (int i = 0; i <= n; i++) buf[i] = 'a'; } int main(void) { f(10); }
- What is printed? c // file1.c int x = 10; // file2.c (same program, separate translation unit) extern int x; void show(void) {…
- What is printed? c int x = 100; void f(void) { int x = 5; { int x = 1; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…