c - 从数组读取段错误(可能与 malloc/realloc 相关)

标签 c arrays memory malloc realloc

我只是想从一个文件中读取一堆 double (每行都有三个 double ,但我不知道事先会有多少行,所以我试图动态分配数组 jm ->vertices.jm->vertices 是一个 (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/

相关文章:

c++ - 使用 'cvMatMul' 时断言错误

php - 如何在php中使用blob图像获取所有数据库记录

node.js - 确保 NODE_OPTIONS --max-old-space-size 正常工作

c - 如果 bool 是 int 的宏,为什么它的大小不同?

java - gc 堆分配和我的 java 程序之间的比率

ruby-on-rails - 如何通过 C 程序的命令行界面编译 C 程序以与我的 ruby​​ gem 一起使用?

c - 关于 POSIX 消息队列和无效参数

c - C中的字符串解析

c - 循环结束条件不起作用 - C

java - 复制数组每隔一个字节的最快方法