I am having segfaulting problems with my program that is supposed to read in a file containing bowling scores and then output your total score, it calls the atoi() function it segfaults.
#include <stdio.h>
#include <stdlib.h>
/*
int myAtoi(char *str)
{
int res = 0, i; // Initialize result
// Iterate through all characters of input string and update result
for (i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
*/
//Cleans and totals the values
int cleanValues(char *values)
{
//debug
puts(values);
//declares vars
int i, total=0, temp;
//iterates through the array converting and totaling the integer values.
for(i=0; i!=37; ++i)
{
//converts and stores the values in temp
temp = atoi(values[i]);
//atoi() returns a zero when it the value is not a number and if the value it is zero it wouldn't mater anyways so in both cases we skip it here.
if(temp != 0)
//adds temp to the total.
total+=temp;
else
//increments i
++i;
//debug
printf("%c %d %d\n",values[i], i, total);
}
//returns the total value which is then returned to the main by readFile()
return total;
}
//reads the file, the name of the file is passed from the main().
int readFile(char *name)
{
//creates the array to hold the read values
char values[37];
//creates a pointer to a memory location where we store the file
FILE *filePointer;
//opens the file for reading
filePointer=fopen(name, "r");
//checks to see if the file contains a information.
if(filePointer == NULL)
{
printf("File %s is not available\n", name);
exit(1);
}
//reads from the file and shoves it into the array
fgets(values, 37, filePointer);
//debugging output for checking the value of values
puts(values);
return cleenValues(values);
}
//the main function... this shouldn't require an explanation... it is the running part of the program! OK there I said it!
int main(int argc, char* argv[])
{
//checks to see if the program has been called correctly using the command line arguments
if(argc!=2)
{
printf("USEAGE: %s nameOfTheInputFile\n", argv[0]);
return 0;
}
//prints the total score by returning the value of mathing()
printf("Your total score is: %d",readFile(argv[1]));
return 0;
}
Does anyone know why it is segfaulting? I am very confused and so is everyone who I have shown to, any and all help is appreciated.
Here is the GDB stepping right before it breaks.
38 temp = atoi(values[i]);
atoi (str=0x39 <Address 0x39 out of bounds>) at Bowling.c:19
19 int res = 0, i; // Initialize result
22 for (i = 0; str[i] != '\0'; ++i)
Program received signal SIGSEGV, Segmentation fault.
0x0000000100401126 in atoi (str=0x39 <Address 0x39 out of bounds>) at Bowling.c:22
22 for (i = 0; str[i] != '\0'; ++i)
1 [main] a 5640 cygwin_exception::open_stackdumpfile: Dumping stack trace to a.exe.stackdump
[Inferior 1 (process 5640) exited with code 0105400]
If i am reading this right, it is saying that the array is exceeding its assigned memory or something.