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);
}
  1. A. Hello, World!, guaranteed by the standard
  2. B. Undefined behaviour: result is a local array, and returning it (decayed to a pointer) leaves s dangling once concat() returns
  3. C. Compile-time error: cannot return a local array
  4. 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

Exams that ask this topic