2015-05-05 53 views
0

我試圖動態分配一個結構數組,但是每當我運行程序時,我不斷得到:a.out(6487,0x7fff7ecb8300)malloc:*對象0x7fff6f670000錯誤:指針爲realloc'沒有被分配d *設置malloc_error_break斷點調試指針被realloced沒有分配

struct node { 
    char course[25]; 
    char category[20]; 
    char prereq[50]; 
    char notes[50]; 
}; 



int main(int argc, char* argv[]) 
{ 
    FILE *fp; 
    char *filename = argv[1]; 
    char *token; 

    char buffer[100]; 
    char *del = ",\n"; 
    int num = 5, i = 0, j =0, count = 0; 
    struct node *d = malloc(num * sizeof(struct node)); 
    char** complete = malloc(num * sizeof(char*)); 
    printf("%s\n", filename); 


    if((fp = fopen(filename, "r")) == NULL) 
    { 
     printf("unable to open %s\n", filename); 
     exit(1); 
    } 
    while(fgets(buffer, sizeof(buffer), fp) != NULL) 
    { 

     if(count == num) 
     { 
      num = num + 5; 
      struct node *d = realloc(d, sizeof(d)*num); 
      printf("Reallocating\n"); 
     } 
     token = strtok(buffer, del); 

     if(strncmp(token, "#", 1) != 0) 
     { 

      strcpy(d[count].course, token); 
      printf("%s\n", d[count].course); 
      strcpy(d[count].category, strtok(NULL, del)); 
      printf("%s\n", d[count].category); 
      strcpy(d[count].prereq, strtok(NULL, del)); 
      printf("%s\n", d[count].prereq); 
      strcpy(d[count].notes, strtok(NULL, del)); 
      printf("%s\n", d[count].notes); 
      count++; 
     } 


    } 
+1

在使用'argv [1]'之前,檢查'argc == 2'。只是一個建議。 –

+1

警告:在'malloc'(等等)中調用'sizeof' [你應該總是把它寫成](http://stackoverflow.com/a/17258659/1151654)作爲'ptr = malloc(sizeof(* ptr) * ...);'而不是'ptr = malloc(sizeof(ptrtype *)* ...);'。 – Eregrith

+1

因此'struct node * d = realloc(d,sizeof(d)* num);'是錯誤的:應該使用'sizeof(* b)'而不是'sizeof(b)' – Eregrith

回答

6
struct node *d = realloc(d, sizeof(d)*num); 

你宣佈一個新的d變量,陰影之前的一個,並養活其尚未初始化值realloc

你需要這樣做:

struct node *newD = realloc(d, num * sizeof *d); 
if(!newD) { 
    // Allocation failure, do something about it and break out 
} /* else */ 
d = newD; 

另外請注意,我糾正了sizeof,其測量指針的大小,而不是指針對象的。

+0

謝謝!這固定了一切! – sukurity

4

在:

struct node *d = realloc(d, sizeof(d)*num); 

聲明一個新的變量d與最初未定值和PAS把它分成realloc。修改成:

struct node *tmp = realloc(d, sizeof(*d)*num); 
if(!tmp) 
    ; // handle error 
d = tmp; 
+0

這是不是分配' sizeof(任何指針)'雖然?我期望'sizeof(struct node)'在那裏。 – usr2564301

+0

@Jongware我糾正了這個問題,但沒有提到它,希望讀者能夠留意。 –