segmentation fault in printf [duplicate] - c

This question already has answers here:
What is the behavior of printing NULL with printf's %s specifier?
(4 answers)
Closed 7 years ago.
Recently I came across this interview question to determine the output of the following printf statements:
printf("test %s\n",NULL);
printf("test %s\n",NULL);
printf("%s\n",NULL);
printf("%s\n",NULL);
test (null)
test (null)
Segmentation fault (core dumped)
I am not able to figure out why does it have a segmentation fault in the last 2 printf's and not for the first 2 cases.

The behavior is undefined.
Standard says
C11- 7.21.6/9
[...] If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
%s in printf expects an argument that should be a pointer to the initial element of an array of character type.

What is the behavior of printing NULL with printf's %s specifier?
Have a look at the above link,i hope it helps!

This is an interview question? The only valid answer is "it will paint your cat green, or maybe do something completely different like travelling to the end of the universe". If they don't accept this as an answer, you don't want to work there.
To be a little more serious here, the output you see is probably created with the GNU C library?
Passing 0 for a %s conversion is undefined behavior and the most probable result of it is a crashing program. glibc has some safety measures built in that replace the string (null) automatically for 0 pointers. You could argue whether this is a great idea, but it's legal because the behavior is undefined -- an implementation can do whatever it wants. Including a crash like you experience it later.

Related

What determines whether segmentation fault occurs? [duplicate]

This question already has answers here:
Why don't I get a segmentation fault when I write beyond the end of an array?
(4 answers)
C - Off by one error, but no segmentation fault?
(3 answers)
No out of bounds error
(7 answers)
Closed 2 years ago.
#include <stdio.h>
int main()
{
int array[10];
array[50] = 5;
printf("array[50] = %i \n", array[50]);
}
Above code works without a problem when is shouldn't. Why is that? This behaviour could make finding a potential bug in the program quite tricky.
The behaviour of an out of bounds array access such as this is undefined.
Undefined behaviour can manifest itself as the program working as you intended!
This does indeed make programming in C tricky, and the language draws criticism for being unsafe in this respect (cf. FORTRAN which grew up contemporaneously). Such pernicious behaviour can be obviated somewhat by adopting appropriate programming practices that have grown up since C was invented in the 1970s. Bounds checking software has also been invented which will weed out bugs such as this.

Two format specifiers but only one argument [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
#include<stdio.h>
int main() {
int j=65;
printf("j>=65?%d:%c\n",j);
return 0;
}
Ok it is understood that in place of %d ,value of j will be printed but why %c is replaced by ö ,i am unable to understand the output of this program , explain the printf statement.
You put doublequotes in a wrong place: you quoted the entire expression, rather than making your format string a conditional:
printf((j >= 65 ? "%d\n" : "%c\n"), j);
Your j >= 65 ? ... : ... expression is part of the string literal. C compiler does not "see" it as anything related to j. Hence the format string contains two format specifiers, with a single printed item; that's undefined behavior.
UB manifests itself in different ways; on your particular system a junk character 'ö' gets printed. This, however, is not a guaranteed behavior - on other systems you may get a different output, or a crash. See this Q&A for an explanation of UB.
This is enough I suppose for explaining whatever you have shown. And the behavior you see can be anything given that it is undefined.
From standard
The fprintf function writes output to the stream pointed to by stream,
under control of the string pointed to by format that specifies how
subsequent arguments are converted for output. If there are
insufficient arguments for the format, the behavior is undefined.
Emphasis mine.
The short answer for this is that this is undefined behavior, the character that gets printed could be anything and the program may even crash.
The longer answer is that old compilers did not check printf strings against the arguments passed, and so by default compilers to not treat this as an error. If you enable the correct warnings (-Wformat) it will complain about this at compile time, and with -Werror the warning will be escalated to an error. Because this is not checked at compile time, as many arguments as are needed are fetched from where they should be on the call stack. This means that first argument after the last specified argument probably has to do with the return address for the stack frame or something, but after that you start to push into unallocated memory. Either way, the behavior is undefined.
If you're interested in more details, this stack overflow answer explains it well.

fflush(stdin) before gets() in c [duplicate]

This question already has answers here:
Using fflush(stdin)
(7 answers)
Closed 8 years ago.
Okay , i was solving a problem in code chef (very easy).
It briefly states that :
-A question as a string will be given , and another string has to be produced which does not have any letter used in question string. Uppercase and lowercase are assumed to be same.
-If all alphabets have been used just print ~ sign.
My whole logic is correct except i caught error in my input and this was caused by using fflush(stdin) before gets(). Please explain why was this an error ? Ignore the rest of the code.
Link to problem :http://www.codechef.com/problems/NOLOGIC/
Link to wrong solution :http://www.codechef.com/viewsolution/3881817
Link to corrected solution :http://www.codechef.com/viewsolution/3881827
Pls Note :In corrected code i have only made change in not using fflush(stdin) and using getchar()
Being that the behavior of fflush(stdin) is implementation specific; and being that the implementation (for this question) is unknown, the behavior will also be unknown.
You may safely expect the behavior of fflush(stdin) to be unpredictable.

C Programming Increment and Decrement Operator Problem [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Undefined behavior and sequence points
(5 answers)
Closed 8 years ago.
$void main()
{
int a=10,c;
c= ++a + ++a;
printf("%d",c);
}
this program Actualy Print Value Of c=24 but By Calculation we can say it should be
c=23 ,how it possible?
Your program has a bug -- you modify the same variable twice without an intervening sequence point. Fix the bug and the mystery will go away.
A very deep understanding of not just how the language works but how compilers work is required to understand why buggy code happens to do what it happens to do. I would just suggest not writing buggy code and, when you find a bug, simply fix it instead of trying to understand precisely why and how it broke.
My advice to you is to stop. You learned the right lesson -- code that triggers undefined behavior is unpredictable and frequently doesn't do what you might expect it to do. That's all you need to know about UB until you're an expert at using the language correctly.
'++' > '+'
Here post increment operation is done before.Since you gave it two times if does post increment two times so the value of 'a' becomes 12 and adds it up (12+12).So the final value is 24.

What is the correct output of this statement? [duplicate]

This question already has answers here:
Turbo C++: Why does printf print expected values, when no variables are passed to it?
(5 answers)
Closed 9 years ago.
int a=9,b=6,c=3;
printf("%d%d%d");
I executed this in code blocks 10.05. I got some garbage values. But in a website the output was given as 3 6 9. What is the correct one?
You will get garbage values, because you're not providing any arguments to the printf() call.
The correct code would be
printf("%d%d%d",c,b,a);
(to get the numbers in the order quoted)
The correct one is neither of the two you described. Since no values were passed to printf, only the formatters, whatever was on the stack at that moment (which is undefined) is passed.
What is the correct output of this statement?
This code invokes undefined behaviour and so there is no correct output. The output is undefined.
The code invokes undefined behaviour because the format string you passed to printf requires you to pass more parameters (3) than you supplied (0).

Resources