c - 如何释放结构数组

标签 c arrays free

我有一个结构 complex 和一个结构 complex_set(一组复数),我有“构造函数”和“析构函数”alloc_setfree_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()

您正在尝试释放每个点。

关于c - 如何释放结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139334/

相关文章:

c - 使用结构数组的学生信息数据库(C语言)

c/linux无限循环应用: deallocate memory if kill -9 command is called

c - 在二进制文件中读取和写入缓冲区

c - 使用 unsigned char 循环

c - fscanf 是否可以同时返回零和消耗输入?

arrays - 两个数组成员的乘法

c++ - Bitshift - 需要解释才能理解代码

arrays - 在 Swift 中保留一组自定义结构

c - 为什么我的函数有时会进入无限循环?

c - 疯狂是免费的()