2013-09-30 31 views
0

我有一個函數用於展開一個數組(圖形)並在最後添加一個新值。這個函數的第一個請求去罰款,但不順心的事,當我做第二次......雙重分配錯誤...?

代碼:

struct station *addStation(struct station *graph, struct station newStation, size_t *stationCount){ 
    size_t newCount = *stationCount+1; 

    graph = realloc(graph, newCount*sizeof(struct station)); 
    *stationCount = newCount; 

    graph[*stationCount] = newStation; 

    return graph; 
} 

和要求:由於的

Station *graph; 
    graph = malloc(146*sizeof(Station)); 

    graph = loadStations(graph, &stationCount); 

    Station newStation = graph[0]; // Dummyvalue 

    printf("StationCount:%d\n",stationCount); 

    graph = addStation(graph, newStation, &stationCount); 

    printf("StationCount:%d\n",stationCount); 

    graph = addStation(graph, newStation, &stationCount); 

第二行圖= addStation ...我在終端中得到一些內存輸出錯誤:

StationCount:146 StationCount:147 resepl ((av) - > bins [((1) - 1)* 2]))__builtin_offsetof((av) - > bsf) (struct malloc_chunk,fd))))& & old_size == 0)|| ((unsigned long)(old_size)> =(unsigned long)((((_builtin_offsetof(struct malloc_chunk,fd_nextsize))+((2 *(sizeof(size_t)))-1)&〜((2 * (爲size_t))) - 1)))& &((old_top) - >大小爲0x1 &)& &((無符號長整數)OLD_END & pagemask)== 0)」失敗。 中止(SIGABRT)(創建打印內存中)

我不明白爲什麼會這樣......

回答

3

C數組從零開始所以具有有效索引[0..newCount-1]

graph[*stationCount] = newStation; 

正在寫入超出分配內存的末尾。這導致未定義的行爲。我猜你的情況是它正在破壞堆管理器用來檢測這種內存損壞的警衛詞。

graph[newCount-1] = newStation; 
+0

大,沒想到的是:

你可以通過改變你寫的數組索引來解決這個問題!謝謝! – theva