2016-11-29 58 views
0

在我試圖理解malloc和結構我所遇到的一個錯誤,我不明白的malloc數組給分段故障

#include <stdio.h> 
#include <stdlib.h> 

typedef struct match 
{ 
    int round; 
} match; 

void foo(match *matches) { 
    for(int i = 0; i < 10; i++) { 
     matches = (match *) realloc(matches, i + 1); 
     matches[i].round = i + 1; 
    } 
} 

int main() 
{ 
    match *matches; 

    matches = (match *) malloc(0); 

    foo(matches); 

    free(matches); 

    return(0); 
} 

所以在我試圖填補這一陣列的比賽dynamicaly失敗

+0

爲什麼的malloc(0)? –

+0

'matches =(match *)realloc(matches,i + 1);'你想要這行嗎? – Danh

回答

2

您的foo功能非常有缺陷。首先,參數傳遞matches指針的副本,因此當您重新分配時,該指針更新foomatches指針,但不更新main中的指針matches。這可能會導致主要的free問題。您需要將參數更改爲foo以成爲雙指針:void foo(match **matches)。然後重新分配,*matches = realloc(...

接下來,realloc的第二個參數是一個大小。但i + 1對於match結構的完整副本來說不夠大。你可能打算做一些像sizeof(struct match) * (i + 1)

1

我除了上面的答案。很好的解釋... ,請以realloc的錯誤,以及使用內存之前,

修改程序

void foo(match **matches) { 
    for(int i = 0; i < 10; i++) { 
     *matches = realloc(*matches, (i+1) * sizeof(match)); 
     ... 
    } 
} 

int main() 
{ 
... 

    foo(&matches); 
... 
}