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

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;
    }

 

  • A.Segmentation fault/code crash
  • B.Executable file name
  • C.Depends on the platform
  • D.Depends on the compiler

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.