简体   繁体   中英

Segfault reading from array (probably malloc/realloc related)

I'm simply trying to read a bunch of doubles from a file (where every line has three doubles, but I DON'T know how many lines there will be beforehand, so I'm trying to dynamically allocate the array jm->vertices. jm->vertices is a (double **).

Here is the code (basic obj model file parser):

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]);
}
//////////////////////????////////////////////////////////////

Can anyone tell me why the memory is not being preserved?

In the call to realloc: sizeof(*jm->vertices) * i+1 should be sizeof(*jm->vertices) * (i+1) .

Your code reallocs a single extra byte. With this change, it allocates enough space for a double* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM