ProgrammingHardHCL · Tech Mahindra pattern
What happens when this runs?
What happens when this runs?
char *concat(const char *a, const char *b) {
char result[100];
strcpy(result, a);
strcat(result, b);
return result;
}
int main(void) {
char *s = concat("Hello, ", "World!");
printf("%s", s);
}- A. Hello, World!, guaranteed by the standard
- B. Undefined behaviour: result is a local array, and returning it (decayed to a pointer) leaves s dangling once concat() returns
- C. Compile-time error: cannot return a local array
- D. Hello, , since strcat silently fails here
Correct answer: B. Undefined behaviour: result is a local array, and returning it (decayed to a pointer) leaves s dangling once concat() returns
result is an automatic (stack) array; concat() returns it decayed to a char*, but its storage is reclaimed the moment concat() returns, leaving s dangling. Reading through s afterward is undefined behaviour — it might 'coincidentally' still show the right text since nothing has overwritten that stack slot yet, but that is never guaranteed, and compilers often warn about exactly this pattern.
More C Programming questions
- What is printed? c int a = 5, b = 2, c = 3; int result = a > b > c; printf("%d", result);
- What is printed? c int a = 1, b = 2, c = 3; int result = a == 1 && b == 2 || c == 100; printf("%d", result);
- What is printed? c int a = 4; int b = ~a + 1; printf("%d %d", b, -a);
- What is printed? c int x = 1, y = 2, z = 3; int result = x < y < z; printf("%d", result);
- What is printed? c int a = 5; int b = a++ + ++a; printf("%d %d", a, b);
- What is printed? c int a = 0; int b = (a = 5) == 5; printf("%d %d", a, b);