Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?

void main()
{
char *p = calloc(100, 1);
p = "welcome";
printf("%s\n", p);
}

 

  • A.Segmentation fault
  • B.garbage
  • C.Error
  • D.welcome

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 *.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.