ndrizza
ndrizza

Reputation: 3415

How to free an array of structs

I have a struct complex and a struct complex_set (a set of complex numbers) and I have the "constructor" and "destructor" functions alloc_set and free_set.

My problem is, that I get the following error in the second iteration of the for loop in free_set:

malloc: *** error for object 0x1001054f0: pointer being freed was not allocated

What is the correct way to deinitialize complex_set? I'm wondering whether the *points property of complex_set needs to be freed only by calling free on the first point (and then it will free the rest) or by freeing each element separately? Or have I already done something wrong in the initialisation?

Here's the code:

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;
}

Upvotes: 1

Views: 934

Answers (2)

Fjotten
Fjotten

Reputation: 357

It's as simple as this: free(set->points);

Upvotes: 1

Russ Schultz
Russ Schultz

Reputation: 2689

You only did one malloc() for set->points, so you should only do one free().

You're trying to free each point.

Upvotes: 4

Related Questions