[英]How to free an array of structs
我有一個struct complex
和一個struct complex_set
(一組復數),並且我有“ constructor”和“ destructor”函數alloc_set
和free_set
。
我的問題是,在free_set
中的for循環的第二次迭代中出現以下錯誤:
malloc: *** error for object 0x1001054f0: pointer being freed was not allocated
反初始化complex_set
的正確方法是什么? 我想知道是否需要僅通過在第一個點上調用free
來釋放complex_set
的*points
屬性(然后它將釋放其余的點)還是分別釋放每個元素? 還是我在初始化中已經做錯了什么?
這是代碼:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.