所以我正在實現一個使用可調整大小的數組的堆,並且每次重新分配內存時都會收到此錯誤。問題是與realloc ..我只是無法弄清楚它有什麼問題。這裏是插入功能:雙免費或腐敗(fasttop)錯誤
void* insert (data_t *data, int room, long wake) {
if(data->size+1 == data->arraySize){
data->arraySize *= 2;
long l = (long)data->arraySize;
int* tempOne = realloc(data->heapElemOne, data->arraySize*sizeof(int));
long* tempTwo = realloc(data->heapElemTwo, l*sizeof(long));
if (tempOne != NULL &&tempTwo !=NULL){ //realloc was
data->heapElemOne = tempOne;
data->heapElemTwo = tempTwo;
}
else{ //there was an error
printf("Error allocating memory!\n");
free(data->heapElemOne);
free(data->heapElemTwo);
return;
}
}
data->size++;
int now = data->size;
/*Adjust its position*/
if(data->size >0){
while(data->heapElemTwo[now/2] > wake && ((now/2)!=0))
{
data->heapElemTwo[now] = data->heapElemTwo[now/2];
data->heapElemOne[now] = data->heapElemOne[now/2];
now /= 2;
}
}
data->heapElemTwo[now] = wake;
data->heapElemOne[now] = room;`
,這裏是主要的部分:
int main(int argc, char *argv[]){
pthread_t r, c;
data_t data;
data.arraySize = 2;
data.size = 0;
long l = (long)data.arraySize;
data.heapElemOne = malloc(data.arraySize * sizeof(int));
data.heapElemTwo = malloc(l * sizeof(long));
這裏的data_t聲明:
typedef struct{
int arraySize;
int* heapElemOne;
long* heapElemTwo;
int size;
int number;
pthread_mutex_t mutex;
pthread_cond_t more;
}data_t;
它搬遷內存4,但是當它正在改變它到8它給出了一個錯誤。在它已經很長時間了,只是無法想象它-_- 在此先感謝!
http://stackoverflow.com/幫助/ mcve – 2014-12-04 06:09:02
無法弄清楚你實際需要什麼。 – Gopi 2014-12-04 06:09:31
是否可以在每次調用'malloc()'和'realloc()'的時候,根據類型的大小,乘以'sizeof(int)'或'sizeof(long)'分配的元素數量你存儲的數據? – ua2b 2014-12-04 06:11:51