Saunders Hayes
Saunders Hayes

Reputation: 31

Please help correct this bug: reading integers line by line from a file using fscanf in c

I tried using this code:

int index = 0; 
int value;
int IntegerArray[MAXARRAYSIZE];
while(fscanf(fp, "%d", &value) == 1){ 
    IntegerArray[index++] = value; 
}

but I received this error:

Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000038 0x98a7c1ea in __svfscanf_l ()

fp is of type FILE and I believe I have used all necessary library inclusions. Please help.

Upvotes: 3

Views: 115

Answers (2)

Samy Vilar
Samy Vilar

Reputation: 11130

you might be exceeding your maxrraysize, as such you are trying to access memory that doesn't belong to your program, so it might be wise to check for that, also please initialize your array just to be safe, since it typically holds what ever previous values where on that location.

int index = 0; 
int value;
int IntegerArray[MAXARRAYSIZE] = {0};

while(fscanf(fp, "%d", &value) == 1){ 
    if (index >= MAXARRAYSIZE)
    {
         printf("reached max array size!\n");
         break ;
    }
IntegerArray[index++] = value; 
}

Upvotes: 1

dirkgently
dirkgently

Reputation: 111210

You need to check if index is less than MAXARRAYSIZE or not. Otherwise, you will be going out of bounds and invoke undefined behavior (typically invalid memory access).

Change

while(fscanf(fp, "%d", &value) == 1)

to

while((1 == fscanf(fp, "%d", &value)) && (index < MAXARRAYSIZE))

You cannot store integers than you have defined the array size.

Upvotes: 2

Related Questions