Discussion
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 *.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development