【发布时间】:2014-04-25 02:37:55
【问题描述】:
我的程序存在段错误问题,该程序应该读取包含保龄球得分的文件,然后输出您的总得分,它调用 atoi() 函数进行段错误。
#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;
}
有人知道为什么会出现段错误吗?我很困惑,我所展示过的每个人也是如此,感谢任何和所有的帮助。
这是 GDB 在中断之前的步骤。
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]
如果我没看错,那就是说数组超出了分配的内存或其他东西。
【问题讨论】:
-
能否请您最小化代码,使其仍能编译和运行,但只包含重现您的错误所需的点点滴滴?
-
通过启用所有编译器警告,您可以节省时间,因为它会立即引导您解决问题。
-
不发出警告的编译器是不合格的,所以我怀疑这更像是 OP 忽略警告的情况。
-
@MihaiMaruseac,将来会这样做,抱歉。 MattMcNabb 是的,总结一下,我是个笨蛋。抱歉这个问题不好,第一次来这里,不知道如何表达:P
标签: c memory segmentation-fault runtime-error atoi