"segfault" error from random seed number?

So, my code randomly started having an issue when it tried to read an input file using the following lines:

char inputName[20] = "params.txt";
FILE *inputFile = fopen(inputName, "r");
char *ptr;

The code is supposed to open a text file, where the following lines of code:

int count = 1;
char singleLine[10];
double parameters[4];
while (count < 5){
    parameters[count] = strtod(fgets(singleLine, 10, inputFile), &ptr);
    count = count + +1;
}
h = parameters[1];
N_steps = parameters[2];
titleNumber = parameters[3];
seed_number = parameters[4];
fclose(inputFile);
inputFile = 0;

And assigns the following values from a .txt files to variables

1.0

100000

1000

33

With the last integer being used as the seed number for the srand() function. However, I have found that some 4-digit and above integers for the seed value cause the code to generate a segmentation fault error. Does anyone know why that is? Is there a range of acceptable seed values for the random number generator function in c?

1 answer

  • answered 2022-01-25 13:51 Vlad from Moscow

    Indices for arrays in C start from 0. If you have an array with N elements then the valid range of indices is [0, N).

    So relative to your code snippet the valid range of indices for this array

    double parameters[4];
    

    is [0, 4 ). The expression parameters[4] accesses memory beyond the array that results in undefined behavior.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum