What is the output of this C code?
void main()
{
char *p = calloc(100, 1);
p = "welcome";
printf("%s\n", p);
}
Answer: D
Correct answer: welcome
The calloc block is allocated and then immediately abandoned: assigning the string literal to p overwrites the only pointer to it. That is a memory leak, but it is not what the question asks about.
p now points at the literal "welcome", so that is what printf outputs. Note that the literal is not modifiable - writing through p afterwards would be undefined behaviour, which is why such a pointer is better declared const char *.
Please log in or register to report this question.