Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault while deferencing a char array

#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?

like image 426
sidchelseafan Avatar asked Apr 19 '26 10:04

sidchelseafan


1 Answers

Could somebody please tell me why I am getting segmentation fault here?

C11: 7.21.6 Formatted input/output functions:

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

3.4.3

1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.

2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

*p is of type char. %s expects argument of type char *. 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

printf("%s",*p);  

to

printf("%s",p);
like image 100
haccks Avatar answered Apr 21 '26 02:04

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!