Why do I get this Segmentation Fault?

Asked

Viewed 90 times

1

Why when I declare:

char *s = "string";

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

I get a Segmentation Fault?

  • You’re trying to record something on Stdin; wouldn’t be for Stdout that you should send the string?

1 answer

5

The code below has the following problems:

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

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

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

[More details after the question is edited] To the code below:

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

When you declare a literal string in a C program, the compiler usually (*) defines these literals at memory addresses that are read-only; then 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 stack (e. g., char s[20] = "string";) or in the heap (e. g., char *s = (char *)malloc(20 * sizeof(char)); strcpy(s, "string");. (**)

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

(**) The use of 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.