Discussion
What will be the output of the following C code (run without any command line arguments)?
#include <stdio.h>
int main(int argc, char *argv[])
{
while (argv != NULL)
printf("%s\n", *(argv++));
return 0;
}
Answer: A
Correct answer: Segmentation fault/code crash
The condition tests argv rather than *argv, and argv is a pointer into the array - it is never itself null however far it is advanced.
The loop therefore never terminates. It prints argv[0], then the terminating null pointer, then whatever lies beyond the array, walking off the end of the block until it reaches unmapped memory and the program is killed. One * separates this from the working version: the null to test for is the one stored in the array.
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