【问题标题】:Segmentation fault while printing first element of string array in c在c中打印字符串数组的第一个元素时出现分段错误
【发布时间】:2013-12-13 01:47:51
【问题描述】:

我正在扫描文本文件中的行并将元素放入特定数组中,sscanf 工作正常并将变量插入数组中,但打印出字符串数组的第一个元素会导致分段错误(打印适用于其他数组中的第一个元素和对于字符串数组中的其余元素)

这是我的代码:

char **shipTable = NULL;
char *notimportant;
double *dirTable;
double *numTable;
double *speedTable;
double *latTable;
double *lngTable;

void scanShips(){
   char fname[30];
   char line[150];
   char shipname[10];
   double lat;
   double lng;
   double speed;
   double dir;
   int numofShips;
   numofShips=1;
   FILE *myfile;



   printf("give file name containing ships /n");
   scanf("%s",fname);
   myfile = fopen(fname,"rt");
   fgets(line,80,myfile);
   sscanf(line, "%d %d %d %d %d %d", &day, &month, &year, &h, &min, &sec);

   while ( fgets( line,100,myfile) != 0 ) {
       sscanf(line, "%s %lf %lf %lf %lf", shipname, &lat, &lng, &dir, &speed);
       printf("%s",shipname);
       printf("\n");

       shipTable = realloc( shipTable, numofShips*sizeof(char*) );
       latTable = realloc( latTable, numofShips*sizeof(double) );
       lngTable = realloc( lngTable, numofShips*sizeof(double) );
       dirTable = realloc( dirTable, numofShips*sizeof(double) );
       speedTable = realloc( speedTable, numofShips*sizeof(double) );
       shipTable[numofShips-1]=malloc((10)*sizeof(char));


       strcpy (shipTable[numofShips-1],shipname);
       dirTable[numofShips-1]=dir;
       speedTable[numofShips-1]=speed;
       latTable[numofShips-1]=lat;
       lngTable[numofShips-1]=lng;

       numofShips++;
   //printf("%d",numofShips);

    }
    fclose ( myfile);

//note:
printf("%s",shipTable[0]);//<---Segmentation fault
printf("%s",shipTable[1]);//<---Perfectly fine, as well as rest fo the array
printf("%f",dirTable[0]);//<---Perfectly fine, as well as rest of "double" arrays

示例文件:
13 11 2011 13 04 00
GW1927 52.408 -4.117 1.000 0.000
GS452 51.750 -4.300 5.000 10.000
EI597 52.100 -6.000 90.000 12.000
EI600 52.000 -5.900 10.000 15.000
EI601 54.000 -5.900 10.000 15.000

船名长度永远不会超过 9 个字符。

【问题讨论】:

  • 数据文件的内容是什么?我怀疑第一个 shipName 的字符数超过了 9 个(==10-1)。尝试增加船名 char shipname[50];shipTable[numofShips-1]=malloc((50)*sizeof(char)); 的长度。另外,我建议使用calloc 而不是malloc
  • 我建议您检查对malloc()realloc() 的调用的返回值。另外,如果shipName 被分配了一个超过 9 个字符的字符串会怎样?
  • 同时检查fopenscanfsscanffgets的返回值。
  • 您可以使用 strdup() 而不是 malloc_strcpy 创建字符串副本。另外,这个示例文件会导致崩溃吗?

标签: c segmentation-fault malloc realloc


【解决方案1】:

您的程序不完整。一旦我完成它(通过添加必要的#includes、定义daymonth 等),它就可以编译并正常工作。

结论:你并没有告诉我们整个故事,错误在于你没有显示的代码中。

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 2013-11-10
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多