【发布时间】:2014-03-11 16:33:39
【问题描述】:
我在 C 中遇到分段错误(核心转储)问题。我正在使用 gcc 进行编译,但我似乎无法修复它!这是代码,它应该查看一个 csv 文件并执行 4 个操作中的 1 个:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
int lines=0, i=0, a=0;
char strings[128], *broken=" ", *array[100][4], *err=" ";
FILE *file;
file=fopen("inventory.csv", "a+");
broken= malloc(1000);
err=malloc(100);
while(fgets(strings, sizeof strings, file)!=NULL){
++lines;
a=0;
broken=strtok(strings, ",");
while(broken!=NULL){
strcpy( array[i][a], broken);
a++;
}
i++;
}
if(strcmp(argv[1], "list")==0){
printf("Name, Quantity, Reorder limit, Cost");
while(fgets(strings, sizeof strings, file)!=NULL){
while(broken!=NULL){
printf("%s, ", array[i][a]);
}
printf("\n");
}
}
else if(strcmp(argv[1], "reorder")==0){
int i=0;
printf("We need to purchase more of the following items: \n");
for(i=0;i<lines;i++){
if(strtod(array[i][1], &err)<=strtod(array[i][2],&err)){
printf("%s\n", array[i][0]);
}
}
}
else if(strcmp(argv[1], "deduct")==0){
if(argv[2]){
int i=0;
char str[100];
for(i=0;i<lines;i++){
if(strcmp(argv[2], array[i][0])==0){
if(strtod(array[i][1],&err)-1>0){
sprintf(str,"%f",strtod(array[i][1],&err)-1);
array[i][1]=str;
printf("Success\n");
fseek(file, 0, 1);
sprintf(str,"%s,%s,%s,%s", array[i][0], array[i][1],
array[i][2], array[i][3]);
fwrite(str,1,sizeof(str),file);
}
else{
printf("There are none left!\n");
}
}
}
}
else{
printf("Enter a food item");
}
}
else if(strcmp(argv[1], "add")==0){
fseek(file, 0, 2);
char str[100];
sprintf(str,"%s,%s,%s,%s\n",argv[2],argv[3],argv[4],argv[5]);
fwrite(str,1,sizeof(str),file);
}
else{
printf("Please enter an argument: list, reorder, deduct _name_, add _name_
_qty_ _reorderlimit_ _price_\n");
}
fclose(file);
return 0;
}
【问题讨论】:
-
file=fopen("inventory.csv", "a+");如果 null 不再继续,最好检查 fopen 的返回值。
-
请使用正确的缩进!
-
strcpy( array[i][a], broken);array[i][a]必须指向为存储字符串保留的区域。
标签: c segmentation-fault coredump