Adding newline character to printf() changes code behaviour

前端 未结 3 1156
遥遥无期
遥遥无期 2021-01-01 11:48

For some reason, adding \\n to printf() changes the behaviour of below code. The code without \\n prints (null) whereas t

3条回答
  •  Happy的楠姐
    2021-01-01 12:23

    The code has undefined behavior in both cases if the program is not given any command line arguments, so anything can happen.

    Since you are curious (good for you!), here is a potential explanation for what you observe:

    • printf("%s\n", argv[1]); can be optimized by the compiler into puts(argv[1]); whereas printf("%s", argv[1]); still invokes printf().

    • some implementations of printf accept a null pointer as an argument for the %s conversion, hence the output (null).

    • puts() has undefined behavior for a null pointer, in your case a segmentation fault.

    Try compiling both without any optimization (-O0) and see if you get (null) output with and without the \n.

    You can play with godbolt's compiler explorer and see how clang changes behavior with -O0, but not gcc.

提交回复
热议问题