【发布时间】:2014-12-04 05:54:58
【问题描述】:
所以我正在使用一个可调整大小的数组来实现一个堆,每次它重新分配内存时我都会收到这个错误。问题在于 realloc ..我只是不知道它有什么问题。这是插入函数:
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 时会出错。搞了这么多年还是想不通-_- 提前致谢!
【问题讨论】:
-
无法弄清楚您实际需要什么。
-
可能是在每次调用
malloc()和realloc()时,您都希望将要分配的元素数乘以sizeof( int )或sizeof( long ),具体取决于您存储的数据类型? -
张贴
data_t的声明。听起来您有pointer和int参考问题。 -
已更新 data_t 声明 :)
标签: c