Why do I receive this Segmentation Fault?

1

Why do I declare:

char *s = "string";

fscanf(stdin, "%s", s);

Do I get a Segmentation Fault?

    
asked by anonymous 17.12.2015 / 20:18

1 answer

5

The code below has the following problems:

char *s = "string";
sprintf(stdin, "%s", s);
  • stdin is of type FILE * , and the first parameter of sprintf is a variable of type char * . Do not mix types, or the result is undefined. To write to FILE * , use fprintf .
  • You can read from the standard entry ; if you want to write , you should use the output pattern.

The code below does what (I think) you want.

void main() {
    char *s = "string";
    fprintf(stdout, "%s", s);
}

[More details after question edit] To the code below:

char *s = "string";
fscanf(stdin, "%s", s);

When you declare a literal string in a program in C, the compiler usually (*) defines these literals in memory addresses that are read-only ; so if you try to modify it, the program will raise a segmentation fault . If you want to avoid this, you can either declare the variable in the heap (e.g., char s[20] = "string"; ) or heap (e.g., char *s = (char *)malloc(20 * sizeof(char)); strcpy(s, "string"); .

(*) This is platform dependent; on some platforms / compilers, your code can work without problems, but you should not count on it.

(**) Using scanf to string functions is dangerous, consider using functions that limit the number of characters read so that there is no danger of buffer overflows.

    
17.12.2015 / 20:26