'scanf ends my program and no error is thrown
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?
Solution 1:[1]
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("%63s", string); so that scanf won't write out of bounds.
Full example:
char string[64];
scanf("%63s", string);
Solution 2:[2]
In this declaration
char *string = "";
there is declared a pointer to an empty string literal that is represented in memory as one byte with the terminating zero value { '\0' }.
And in this call
scanf("%s", string);
you are trying to change the string literal pointed to by the pointer string. Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
By this reason it is always better to declare pointers to string literals with the qualifier const.
const char *string = "";
By the way in C++ opposite to C string literals have types of constant character arrays. So for such a declaration in C++
char *string = "";
the C++ compiler will issue a message.
If you want to enter more than one character then declare a character array as for example
char string[10] = "";
and use the following call of scanf
scanf( "%9s", string );
If you want to enter only one character then declare an object of the type char as for example
char c = '\0';
and use the following call of scanf
scanf( " %c", &c );
Solution 3:[3]
try this:
char string[50]; // [ the max of letters you want in your string ]
printf("whats your fav letter?: ");
scanf("%s", string);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Abdelmoula Bilel |
