2014-02-24 55 views
1

我只是試圖從文件中讀取一堆雙打(每行有三個雙打,但我不知道預先會有多少行,所以我試圖動態分配陣列jm->頂點jm->頂點是(雙**)Segfault從數組讀取(可能malloc/realloc相關)

下面是代碼(基本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]); 
} 
//////////////////////????//////////////////////////////////// 

誰能告訴我爲什麼內存不被保留?

+0

你初始化jm-> nvert爲0嗎? – immibis

+0

是的,jm-> nvert被初始化。 – h4x0rjax

回答

2

在調用realloc:sizeof(*jm->vertices) * i+1應該是sizeof(*jm->vertices) * (i+1)

您的代碼重新分配一個額外的字節。有了這個改變,它爲double*分配了足夠的空間。