gpt4 book ai didi

C 列出被释放对象的错误校验和

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:35 25 4
gpt4 key购买 nike

我正在尝试为调整大小的数组编写 C 结构,但出现错误:

a.out(34254,0x7fffa17b7340) malloc: *** error for object 
0x7fdd39c02908: incorrect checksum for freed object - object was
probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
[1] 34254 abort ./a.out

这是我目前拥有的代码:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>

typedef struct List {
int length;
int *vals; // This should be generic somehow
int curr_inserted;
int max_allowed;
} List;

List *initialize(int val) {
List *curr;
curr = malloc(5 * sizeof(int));
if (curr == NULL) {
printf("Memory Allocation Error\n");
exit(1);
} else {
curr->length = 1;
curr->vals = malloc(10 * sizeof(int));
curr->vals[0] = val;
curr->curr_inserted = 1;
curr->max_allowed = 10;
}
return curr;
}
void add(List *x, int val) {
if (x->curr_inserted == x->max_allowed) {
int* bigger_arr = realloc(x->vals, (2 * x->max_allowed));
x->vals = bigger_arr;
x->max_allowed *= 2;
}
x->vals[x->curr_inserted] = val;
x->length++;
x->curr_inserted++;
}

我正在初始化和检查这样的值:

int main() {
List *x = initialize(10);
for (int i = 0; i < 100; i++) {
add(x,i);
}
for (int i =0; i < x->length; i++) {
printf("val %d is %d\n",i,x->vals[i]);
}
free(x);
return 0;
}

我认为错误出在我尝试调整大小的添加方法中,但我不太清楚如何处理此错误。

最佳答案

int* bigger_arr = realloc(x->vals, (2 * x->max_allowed));

会是

int* bigger_arr = realloc(x->vals, (2 * x->max_allowed*sizeof(int)));

但是您 realloc 的方式是错误的,因为 realloc 也可能会失败。您应该在分配之前检查它返回的内容。

还有 curr = malloc(5 * sizeof(int)); 将是curr = malloc(sizeof(List)); 因为对于结构,您无法通过添加单个成员元素的大小来计算它需要的分配内存。总是有填充的可能性,在这种情况下它会失败。

关于C 列出被释放对象的错误校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48067359/

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