gpt4 book ai didi

c - 双重释放或损坏(fasttop)错误

转载 作者:行者123 更新时间:2023-11-30 17:24:13 27 4
gpt4 key购买 nike

所以我正在使用可调整大小的数组实现堆,每次重新分配内存时我都会收到此错误。问题在于 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(data.arraySize)

此调用以及对 mallocrealloc 的所有其他调用都是错误的。你想要

malloc(data.arraySize * sizeof(int)) 

或分别

malloc(data.arraySize * sizeof(long)) 

根据您的元素类型。 malloc 及其 friend 接受以字节为单位的分配大小,并且 intlong 通常大于 1 个字节。因此,您的数组分配得太短,并且缓冲区会溢出。

关于c - 双重释放或损坏(fasttop)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27287259/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com