如何释放结构数组
How to free an array of structs
我有一个结构 complex
和一个结构 complex_set
(一组复数),我有 "constructor" 和 "destructor" 函数 alloc_set
和 free_set
.
我的问题是,在 free_set
中 for 循环的第二次迭代中出现以下错误:
malloc: *** error for object 0x1001054f0: pointer being freed was not allocated
取消初始化的正确方法是什么complex_set
?我想知道 complex_set
的 *points
属性 是否只需要通过在第一点调用 free
来释放(然后它将释放其余部分)或通过释放每个元素分别?还是我在初始化时已经做错了什么?
代码如下:
typedef struct complex complex;
typedef struct complex_set complex_set;
struct complex { double a; double b; };
struct complex_set {
int num_points_in_set;
complex *points; // an array of struct complex
};
struct complex_set *alloc_set(complex c_arr[], int size) {
complex_set *set = (complex_set *) malloc(sizeof(complex_set));
set->num_points_in_set = size;
// i think i may even just use the pointer c_arr as '*points'
// however, i want to make sure malloc was called
set->points = (complex *) malloc(size*sizeof(complex));
for (int i=0; i<size; i++) {
set->points[i] = c_arr[i];
}
return set;
}
void free_set(complex_set *set) {
complex *current = set->points;
complex *next = NULL;
int iterations = set->num_points_in_set;
for(int i=0; i<iterations; i++) {
next = current + 1;
// i get the error here, in the second iteration:
free(current);
current = next;
}
free(set);
set = NULL;
}
您只为 set->points
做了一个 malloc()
,所以您应该只做一个 free()
。
您正在尝试释放每个点。
就这么简单:
free(set->points);
我有一个结构 complex
和一个结构 complex_set
(一组复数),我有 "constructor" 和 "destructor" 函数 alloc_set
和 free_set
.
我的问题是,在 free_set
中 for 循环的第二次迭代中出现以下错误:
malloc: *** error for object 0x1001054f0: pointer being freed was not allocated
取消初始化的正确方法是什么complex_set
?我想知道 complex_set
的 *points
属性 是否只需要通过在第一点调用 free
来释放(然后它将释放其余部分)或通过释放每个元素分别?还是我在初始化时已经做错了什么?
代码如下:
typedef struct complex complex;
typedef struct complex_set complex_set;
struct complex { double a; double b; };
struct complex_set {
int num_points_in_set;
complex *points; // an array of struct complex
};
struct complex_set *alloc_set(complex c_arr[], int size) {
complex_set *set = (complex_set *) malloc(sizeof(complex_set));
set->num_points_in_set = size;
// i think i may even just use the pointer c_arr as '*points'
// however, i want to make sure malloc was called
set->points = (complex *) malloc(size*sizeof(complex));
for (int i=0; i<size; i++) {
set->points[i] = c_arr[i];
}
return set;
}
void free_set(complex_set *set) {
complex *current = set->points;
complex *next = NULL;
int iterations = set->num_points_in_set;
for(int i=0; i<iterations; i++) {
next = current + 1;
// i get the error here, in the second iteration:
free(current);
current = next;
}
free(set);
set = NULL;
}
您只为 set->points
做了一个 malloc()
,所以您应该只做一个 free()
。
您正在尝试释放每个点。
就这么简单:
free(set->points);