从数组中读取Segfault(可能是malloc / realloc相关)

时间:2014-02-24 02:10:49

标签: c arrays memory malloc realloc

我只是想从一个文件中读取一堆双打(每行有三个双打,但我不知道预先有多少行,所以我试图动态分配数组jm - >顶点.jm->顶点是(双**)。

这是代码(基本obj模型文件解析器):

jm->vertices = malloc(sizeof(double *));
jm->vertices[0] = malloc(sizeof(double) * 3);
while(strcmp(theS,"v") == 0){

/*vertices stores the x y z of vertices in a 2d array*/
    if(i != 0){
        /*TRYING TO REALLOC*/
        if((jm->vertices = (double **)realloc(jm->vertices, sizeof(*jm->vertices) * i+1)) == NULL){
            fprintf(stderr,"Error allocating memory. Exitting\n");
            exit(1);
        }

        jm->vertices[i] = malloc(sizeof(double) *3);
    }

    printf("%s\n",theS);

    if(fscanf(fp, "%lf", &jm->vertices[i][0]) != 1){fprintf(stderr, "Error: Not enough vertices"); exit(0);}

    if(fscanf(fp, "%lf", &jm->vertices[i][1]) != 1){fprintf(stderr, "Error: Not enough vertices"); exit(0);}

    if(fscanf(fp, "%lf", &jm->vertices[i][2]) != 1){fprintf(stderr, "Error: Not enough vertices"); exit(0);}

    /*CAN PRINT HERE FOR SOME REASON*/
    printf("#:%d // %.8lf %.8lf %.8lf\n", i+1,jm->vertices[i][0], jm->vertices[i][1], jm->vertices[i][2]);

    theS[0] = '\0';

    fscanf(fp, "%s", theS);


    if(theS[0] == '#'){
        comment =1;
        while(theS[0] == '#'){
            theS[0] = '\0';
            fgets(theS, 70, fp);
            theS[0] = '\0';
            fscanf(fp, "%s", theS);
        }
        break;
    }

    if(strcmp(theS, "vn") == 0){break;}
                                                                                                                                  48,0-1        11%
    if(strcmp(theS, "g") == 0){
        theS[0] = '\0';
        fscanf(fp, "%s", theS);
        theS[0] = '\0';
        fscanf(fp, "%s", theS);
        theS[0] = '\0';
        fscanf(fp, "%s", theS);
        theS[0] = '\0';
        fscanf(fp, "%s", theS);
        break;
    }
    if(comment == 1){break;}
    i++;

    jm->nvert++;
}
i=0;

/*THIS CODE SEGFAULTS*/////////////////////////////////////////////////
for(i=0; i<jm->nvert-1; i++){
    printf("%.8lf %.8lf %.8lf", jm->vertices[i][0], jm->vertices[i][1], jm->vertices[i][2]);
}
//////////////////////????////////////////////////////////////

有谁能告诉我为什么没有保存记忆?

1 个答案:

答案 0 :(得分:2)

在对realloc的调用中:sizeof(*jm->vertices) * i+1应为sizeof(*jm->vertices) * (i+1)

您的代码重新分配一个额外的字节。通过此更改,它为double*分配了足够的空间。