Home > database >  How to fix 'Segmentation fault' while redirecting input in C
How to fix 'Segmentation fault' while redirecting input in C

Time:03-21

I've searched for solutions to that problem and couldn't find any that match mine.

I wrote a program that gets two arrays of integers and return the scalar product between them. It works fine when I'm submitting the input manually, but when I try to read the input from a text file, I encounter that Segmentation fault.

Edit: I'm talking about stdin redirection

I would be grateful for some help.

The code is:

#include <stdio.h>
#define MAXLIMIT 100

int scalar_product(int[], int[], int);
void set_array(int[]);

int main(){
    int arr1[MAXLIMIT], arr2[MAXLIMIT];
    int size, result;

    set_array(arr1);
    set_array(arr2);

    printf("Enter the vectors' dimension: ");
    scanf("%d", &size);

    result = scalar_product(arr1, arr2, size);
    printf("The scalar product is: %d \n", result);
    
    return 0;
}

void set_array(int a[]){
    int i;
    printf("Please enter a vector with up to %d elements: \n", MAXLIMIT);
    for (i = 0; i < MAXLIMIT - 1 && (scanf("%d", &a[i]) != EOF); i  );
}

int scalar_product(int a1[], int a2[], int size){
    int product = 0, i;
    for (i = 0; i < size; i  ){
        product  = a1[i] * a2[i];
    }
    return product;
}

and the text file contains:

1 -2 3 -4
6 7 1 -2
4

CodePudding user response:

HEre

   void set_array(int a[]) {
       int i;
       printf("Please enter a vector with up to %d elements: \n", MAXLIMIT);
         for (i = 0; i < MAXLIMIT - 1 && (scanf("%d", &a[i]) != EOF); i  );
    }

When reading from the console you will never hit EOF (unless you enter ctrl-D which I guess you didnt) so your set_array loops just keep going, reading from the file. You read all the data in the first set_array and read nothing in the second one because you have finished the input file

the actualk failure was that you ran off the end of the file, so the scanf of size failed and you were trying to read a random sized array in the function scalar_product.

Test the return from scanf always

What you need to do is put a count in the file before the first array so you know how many items to read into arr1 and I suggest a count before the second lot too.

ie

 void set_array(int a[]) {
    int i;
    int count = 0;
    
    printf("Please enter how many elements you want to enter, max = %d \n", MAXLIMIT);
    scanf("%d", &count);
    if(count > MAXLIMIT) count = MAXLIMIT;
    for (i = 0; i < count && (scanf("%d", &a[i]) != EOF); i  );
 }
  •  Tags:  
  • c
  • Related