Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding newline character to printf() changes code behaviour

Tags:

People also ask

How to put newline in printf?

Try this: printf '\n%s\n' 'I want this on a new line! ' That allows you to separate the formatting from the actual text.

Does printf print a newline?

The printf statement does not automatically append a newline to its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string.

How to add new line in c programming?

In most C compilers, including ours, the newline escape sequence '\n' yields an ASCII line feed character. The C escape sequence for a carriage return is '\r'.

How to print statement in next line in C?

Using %c to print the new line We can use the %c within the string in printf() statement with the value 0x0A, 10 or '\n'.


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

Printf.c

#include <stdio.h>  int main(int argc, char* argv[]){     printf("%s", argv[1]); }  

Printf.c - Output

$ gcc -o Printf Printf.c $ ./Printf (null) 

Printf_Newline.c

#include <stdio.h>  int main(int argc, char* argv[]){     printf("%s\n", argv[1]); } 

Printf_Newline.c - Output

$ gcc -o Printf_Newline Printf_Newline.c $ ./Printf_Newline Segmentation fault (core dumped) 

I am curious to understand the reason behind this.