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[])
{
printf("%s\n", argv[argc]);
return 0;
}
Answer: A
Correct answer: Segmentation fault/code crash
With no arguments argc is 1, so argv[argc] is argv[1] - the guaranteed null pointer at the end of the vector.
Passing a null pointer to %s is undefined behaviour, and the crash the key reports is what an implementation that simply dereferences it produces. The GNU C library instead detects the case and prints (null), which is why the same construct appears elsewhere with that answer - the code is unsafe either way and its result cannot be relied on.
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