C 动态调整作为双指针传入的数组的大小:检测到双自由
TL;DR:我是否正确地将数组传递到grow()中? 我试图在向数组添加元素时动态调整数组大小。目前我收到一条错误消息:C 动态调整作为双指针传入的数组的大小:检测到双自由,c,C,TL;DR:我是否正确地将数组传递到grow()中? 我试图在向数组添加元素时动态调整数组大小。目前我收到一条错误消息: free(): double free detected in tcache 2 我很确定我在某种程度上错误地传递了这个论点,但我对指针比较熟悉,所以我可以使用提示。这是我的主要功能,我已经去掉了大部分。问题最像add()和grow()方法 编辑:我应该补充一点,如果我绕过add(),只要试着从main调用grow(),它就会正常工作 main: int main(int
free(): double free detected in tcache 2
我很确定我在某种程度上错误地传递了这个论点,但我对指针比较熟悉,所以我可以使用提示。这是我的主要功能,我已经去掉了大部分。问题最像add()和grow()方法
编辑:我应该补充一点,如果我绕过add(),只要试着从main调用grow(),它就会正常工作
main:
int main(int argc, char *argv[]){
// declaring the dynamic array
const int SIZE = 2;
float * q;
q = (float*)malloc(sizeof(float) * SIZE); // initial memory allocation
int tail = 0; // tail is the index in which we will add items
int capacity = SIZE;
// add stuff to the array
add(10.0, q, &tail, &capacity);
add(20.0, q, &tail, &capacity); // crashes during this call!
return 0;
}
void add(float element, float* q, int* tail, int* capacity){
// add the element
q[*tail] = element;
// increment tail
++*tail;
// do we need to resize the array?
if(*tail >= (*capacity) / 2){
// capacity is already an int* so we don't need the & symbol
grow(&q, *capacity);
// update capacity
*capacity = (*capacity) * 2;
}
return;
}
下面是我的add()和grow()方法,它们包含在另一个文件中。在我第二次给grow打电话之前,一切似乎都很顺利。添加:
int main(int argc, char *argv[]){
// declaring the dynamic array
const int SIZE = 2;
float * q;
q = (float*)malloc(sizeof(float) * SIZE); // initial memory allocation
int tail = 0; // tail is the index in which we will add items
int capacity = SIZE;
// add stuff to the array
add(10.0, q, &tail, &capacity);
add(20.0, q, &tail, &capacity); // crashes during this call!
return 0;
}
void add(float element, float* q, int* tail, int* capacity){
// add the element
q[*tail] = element;
// increment tail
++*tail;
// do we need to resize the array?
if(*tail >= (*capacity) / 2){
// capacity is already an int* so we don't need the & symbol
grow(&q, *capacity);
// update capacity
*capacity = (*capacity) * 2;
}
return;
}
成长
void grow(float* *q, const int capacity){
printf("# start of grow... capacity = %d\n", capacity);
// creating temp array
float * tmp = (float*)malloc(sizeof(float) * (capacity * 2));
// copying values
int i;
for (i = 0; i < capacity; ++i){
tmp[i] = (*q)[i];
}
// de-allocate old q
free(*q);
// re-assign
*q = tmp;
}
void增长(浮点**q,常量整数容量){
printf(“开始增长…容量=%d\n”,容量);
//创建临时数组
浮动*tmp=(浮动*)malloc(浮动大小)*(容量*2));
//复制值
int i;
对于(i=0;i
传递内部q
,用于add
。不是原来的那个。与更改任何其他参数(例如,element=1.0
)一样,它不会影响main
中的q
你应该通过考试
void add(float element, float* *q, int* tail, int* capacity){
* * *
grow(q, *capacity);
就这样说吧
add(10.0, &q, &tail, &capacity);
为了使
q
本身可变,正如tail
和capacity
当前一样。另外,grow
可以很容易地替换为realloc()
您正确地传递到了grow
,但没有正确地传递到add
。除此之外,我建议重新设计,将q
、capacity
和tail
放入结构中<代码>添加(20.0,&q,&tail,&capacity)对调用方来说太麻烦了。我明白了,我正在更新本地版本!这就可以解释了。谢谢