Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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("%64s", string); so that scanf won’t write out of bounds.

Full example:

char string[64];
scanf("%64s", string);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading