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

3

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.

c
arrays
scanf
asked on Stack Overflow Jun 15, 2012 by Saunders Hayes • edited Jun 15, 2012 by dirkgently

2 Answers

2

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.

answered on Stack Overflow Jun 15, 2012 by dirkgently
1

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; 
}
answered on Stack Overflow Jun 15, 2012 by Samy Vilar • edited Jun 15, 2012 by Samy Vilar

User contributions licensed under CC BY-SA 3.0