#include<stdio.h>
int main(void)
{
char * p= "strings are good";
printf("%s",*p);
return 0;
}
Could somebody please tell me why I am getting segmentation fault here?
#include<stdio.h>
int main(void)
{
char * p= "strings are good";
printf("%s",*p);
return 0;
}
Could somebody please tell me why I am getting segmentation fault here?
C11: 7.21.6 Formatted input/output functions:
3.4.3
*p
is of typechar
.%s
expects argument of typechar *
. This will invoke undefined behavior. In this case anything could happen. Sometimes you may get the expected result and sometimes not. This may also cause program crash or segmentation fault (which is the case here).For
%s
, you need to pass the starting address of the sting/literal.Change
to
You are passing a single char as a string type(%s) in printf formatted output. Change it to p
Here's the problem:
printf
will parse theconst char *
format string, in your case:"%s"
, and will deduce that the first argument other than the format will be achar *
, too.Now, because you dereference the pointer, you're passing a single char (
char
, without the*
)Now if you compare the size of a char to the size of a char pointer:
You'll see that a char pointer is 4 (or 8 for 64 bits) times the size of a char.
Consider what you're actually doing as forcing
printf
to cast the value of a char to a pointer, and then use that pointer to read a string:Output:
The solution:
Don't dereference the pointer, just pass it as is.
Just a little tip: learn to love the storage class modifier
const
. It's a useful reminder in this case:Whereas:
The
const
is a visual reminder that whatever you're going to do withp
, you should keep in mind that it points to a constant, and the value can't be edited.