Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is scanf not working as expected when writing to a string literal? [duplicate]

Tags:

c

scanf

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....

like image 294
vimalpt Avatar asked Oct 24 '22 09:10

vimalpt


2 Answers

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.

like image 153
Sergey Kalinichenko Avatar answered Nov 27 '22 19:11

Sergey Kalinichenko


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 chars (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.

like image 29
Arkku Avatar answered Nov 27 '22 18:11

Arkku