txt解析C中的分段错误

时间:2013-09-17 17:02:11

标签: c gdb

您好我正在尝试解析每行中有2个双打的txt文件。在第一行有一个整数,它是txt文件的总行数。我有一个Nx2矩阵的双倍COORD [NPOIN] [2]我希望将每个txt行的第一个双重放入COORD [IPOIN] [0],第二个放入COORD [IPOIN] [1]。下面代码的一部分应该启发你:D

COORD = (double**)malloc(NPOIN*sizeof(double*)); 

for(int i=0; i<NPOIN; i++)
{
  COORD[i] = (double*)malloc(NDIME*sizeof(double));
}

fin = fopen("coord", "r");
fgets(line, 256, fin);
NPOIN = atoi(line);
char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++)
{
   fgets(line, 256, fin);
   token = strtok(line," \t" );
   COORD[IPOIN][0] = atof(token); //line 891          
   token = strtok(NULL, " \t");
   COORD[IPOIN][1] = atof(token);

}

我编译代码,一切都好。但是当我运行它时,gdb在第891行显示分段错误。任何人都可以给出一些建议吗?我被卡住了!

1 个答案:

答案 0 :(得分:5)

以下是使用printf进行调试的方式:
虽然您应该学会使用GDB或其他调试器

逐步完成代码
fin = fopen("coord", "r");
if (fin == NULL)  printf("failed to open\n");


fgets(line, 256, fin);
printf("Got first line as %s\n", line);

NPOIN = atoi(line);
printf("NPOIN is now %d\n", NPOIN);

char *token;

for(IPOIN=0; IPOIN<NPOIN; IPOIN++){
      fgets(line, 256, fin);
      printf("Got a line as %s\n", line);

      token = strtok(line," \t" );
      printf("Got token #1 %s\n", token);

      COORD[IPOIN][0] = atof(token); //line 891
      printf("Found float %f\n", COORD[IPOIN][0]);

      token = strtok(NULL, " \t");
      printf("Got token #2 %s\n", token);
      COORD[IPOIN][1] = atof(token);
      printf("Found float %f\n", COORD[IPOIN][1]);
}