我只是试图从一个文件中读取一组双倍(其中每行有三个双倍,但我不知道事先会有多少行,所以我试图动态分配数组jm->顶点。jm->顶点是a(double**)。
下面是代码(基本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]);
}
//////////////////////????////////////////////////////////////

有人能告诉我为什么记忆没有被保存下来吗?

最佳答案

在调用realloc时:sizeof(*jm->vertices) * i+1应该是sizeof(*jm->vertices) * (i+1)
您的代码会重新定位一个额外的字节。通过这个更改,它为double*分配了足够的空间。

关于c - 从数组读取段错误(可能与malloc/realloc相关),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21977713/

10-11 21:46