Why am I getting a segmentation fault when using fgets and sscanf in a for loop?

3819 views c
-1

The goal of this is to enter in 8 integers and then print the sequence backwards. When I run this I am able to enter one integer before I am given a seg fault.

#include <stdio.h>
int main() {
int eight[8];
int i;
char s[100];
for(i = 0; i < 8; i++){
    printf("Please enter an integer \n");
    fgets(s, 100, stdin);
    sscanf(s, "%d", eight[i]);
}
for(; i > 0; i--){
    printf("%d", eight[i]);
}
return 0;

answered question

Because eight[i] is not a valid pointer to an int?

You should be testing the return value of fgets() to make sure it actually read a line and didn't get EOF or an error instead. You should be testing the return value of sscanf() (ensure that it is 1) so you know whether the string entered could be interpreted as a number. (But your problem is what @immibis says: you need &eight[i] and not eight[i] in the call to sscanf().)

I tried it with &eight[i] in the sscanf call and it still gives a seg fault. Also, I'm new so I'm not exactly sure how to test the return value.

@HoneyBunchers 1) Insure you applied & here sscanf(s, "%d", &eight[i]); and not printf("%d", eight[i]);. 2) enable all compiler warnings to save time.

testing the returned value from scanf() if( sscanf(s, "%d", &eight[i]) != 1 ) { fprintf( stderr, "sscanf failed to extract an integer\n" ); }

at this point: for(; i > 0; i--){ the variable i will contain 8. when indexing into an array (in C) the valid indexes are (0...number of entries in array -1 ) so the first loop execution will be accessing beyond the end of the array eight[] resulting in undefined behavior

Okay sorry guys I think I forgot to recompile when I added the &. Thanks for the help everyone it works now.

1 Answer

3

In sscanf() you have to give a pointer to the variable in which you want to store the value; sscanf(s, "%d", &eight[i]);.

This https://www.tutorialspoint.com/c_standard_library/c_function_sscanf.htm page says:

other arguments ? This function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order.

For each format specifier in the format string that retrieves data, an additional argument should be specified. If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like: int n; sscanf (str,"%d",&n);

The segmentation fault occurs because instead of a valid pointer, sscanf() gets the value of eight[i].

posted this

Have an answer?

JD

Please login first before posting an answer.