我有一個函數用於展開一個數組(圖形)並在最後添加一個新值。這個函數的第一個請求去罰款,但不順心的事,當我做第二次......雙重分配錯誤...?
代碼:
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)(創建打印內存中)
我不明白爲什麼會這樣......
大,沒想到的是:
你可以通過改變你寫的數組索引來解決這個問題!謝謝! – theva