include<stdio.h>
int main()
{
//char b[10];
char *a="goodone";
//a=b;
scanf("%s",a);//this scanf fails and thow segmentation fault.
printf("%s",a);
}
Why is this not working? I tried a lot with this scanf but, when I reserve memory for my variable a*(by assigning a=b (commented)) it works fine. Otherwise it doesn't. I believe that char *a will allocate some memory for its string,("goodone")and return that memory location to its value. And printf working fine with this belief why scanf not? please save me from this....
This is because you are instructing scanf
to write the data that it reads into the memory allocated for the const char*
value, i.e. into read-only memory.
If you would like to make your string constant writable, change
char *a="goodone";
to
char a[]="goodone";
Note that this is not safe either: it may crash when the user enters more than seven characters. Add a limit to your format specifier in order to address that issue:
scanf("%7s",a);
P.S. The commented out a=b
works fine because it is not modifying the string constant; rather, it modifies a pointer to character constant, which is allowed.
char *a
is just a pointer to a char
. When you assign "goodone"
to it, it points to that string literal (which is read-only), and scanf
tries to overwrite that string in memory which causes the crash.
If you assign b
to it, then you have a
pointing to a writeable memory area of 10 char
s (i.e., a string of maximum length 9 + the terminating NUL). So it works as long as scanf
is not storing anything longer than that in there.
Likewise you could make a
an array instead of a pointer (i.e., char a[] = "goodone";
). Again you need to watch out not to store anything longer in there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With