I am a beginner in C and I encountered problems when dealing with scanf
, hoping for an explanation behind this
this is my code
#include <stdio.h>
#include <math.h>
#include <string.h>
int fav_charac() {
char *string = "";
printf("whats your fav letter?: ");
scanf("%s", string); // the problem
printf("your fav letter is %s\n", string);
}
int main() {
fav_charac();
return 0;
}
and this is the program running
whats your fav letter?: a
C:\Users\DELL\source\repos\hello C\x64\Debug\hello C.exe (process 15052) exited with code -1073741819.
Press any key to close this window . . .
as you can see it exited right after an input is made, why?
CodePudding user response:
The scanf
will attempt to write to string
, which is .rodata
. That means, the Data in string
can only be read from but not written to. Use char string[64];
or something similar. This will place the variable into .data
. Also limit user input in scanf
with scanf("ds", string);
so that scanf won't write out of bounds.
Full example:
char string[64];
scanf("ds", string);
CodePudding user response:
try this:
char string[50]; // [ the max of letters you want in your string ]
printf("whats your fav letter?: ");
scanf("%s", string);