OA. free
Free
IBM Core Computer Science Core Computer Science Medium

Question 14: What will be the last printf() output?

IBM technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What will be the last printf() output?**

char * get_str(const char *str)
{
    char buf[100];
    printf("buf=0x%llX\n", (uint64_t)buf);
    strcpy(buf, str);
    return (char *)buf;
}

void mod_str()
{
    char buf[100];
    printf("buf=0x%llX\n", (uint64_t)buf);
    int i;
    for (i = 0; i < sizeof(buf) - 1; i++)
        buf[i] = 'A';
    buf[sizeof(buf) - 1] = '\0';
}

int main()
{
    char mybuf[100];
    int i;
    char *s = get_str("hello");
    mod_str();
    for (i = 0; i < 5; i++)
        mybuf[i] = s[i];
    mybuf[5] = '\0';
    printf("s=[%s]\n", mybuf);
    
    return 0;
}

Pick ONE option:

Choose one option.
Show answer & explanation
Answer: C. s=[AAAAA]

The pointer s returned by get_str() points to a local buffer that is reused by mod_str(). When mod_str() executes, it fills its local buf (which occupies the same stack memory location) with 'A' characters, overwriting the "hello" string. When main() copies 5 characters from s, it reads the first 5 'A' characters that now occupy that memory location.

Step-by-step Derivation:

  1. get_str("hello") creates a local buffer and returns a pointer to it. The function returns, but the pointer still points to that stack location.
  2. mod_str() declares its own local buf[100], which typically reuses the same stack memory location as the previous get_str() call (stack frames are reused).
  3. mod_str() fills this buffer with 'A' characters (all 99 positions), overwriting the "hello" string at that memory location.
  4. Back in main(), the loop copies 5 characters from s into mybuf. Since s now points to memory filled with 'A's, mybuf receives "AAAAA".
  5. The final printf outputs: s=[AAAAA]