ProgrammingHardWipro · Cognizant pattern
What happens when this runs?
What happens when this runs?
char buf[5];
strcpy(buf, "hello world");
printf("%s", buf);- A. It safely truncates to fit buf's 5 bytes
- B. Undefined behaviour: strcpy writes past the end of buf (a 12-byte string into a 5-byte buffer), a classic buffer overflow
- C. Compile-time error: the string literal is too long for buf
- 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
- What happens when this runs? c int divide(int a, int b) { return a / b; } int main(void) { printf("%d", divide(10, 0)); }
- What happens when this runs? c int p = (int )malloc(3 sizeof(int)); if (p == NULL) { return 1; } p[0] = 1; p[1] = 2; p[2] = 3; free(p)…
- What happens when this runs? c int arr[10]; for (int i = 0; i <= 10; i++) { arr[i] = i; } printf("done");
- What is printed? c #define CONCAT(a, b) a##b int main(void) { int xy = 100; printf("%d", CONCAT(x, y)); }
- What is printed? c #if defined(FEATUREX) && !defined(FEATUREY) #define MODE 1 #elif !defined(FEATUREX) #define MODE 2 #else #define MODE 3…
- What is printed? c #define INCREMENT(x) x = x + 1 int main(void) { int a = 5, b = 10; if (a > 0) INCREMENT(a); else INCREMENT(b)…