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:
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:
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.mod_str()declares its own localbuf[100], which typically reuses the same stack memory location as the previousget_str()call (stack frames are reused).mod_str()fills this buffer with 'A' characters (all 99 positions), overwriting the "hello" string at that memory location.- Back in
main(), the loop copies 5 characters fromsintomybuf. Sincesnow points to memory filled with 'A's,mybufreceives "AAAAA". - The final printf outputs:
s=[AAAAA]