c - How to free an array of structs -


i have struct complex , struct complex_set (a set of complex numbers) , have "constructor" , "destructor" functions alloc_set , free_set.

my problem is, following error in second iteration of loop in free_set:

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

what correct way deinitialize complex_set? i'm wondering whether *points property of complex_set needs freed calling free on first point (and free rest) or freeing each element separately? or have done wrong in initialisation?

here's 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; // 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;     // think may use pointer c_arr '*points'     // however, want make sure malloc called     set->points = (complex *) malloc(size*sizeof(complex));     (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;         // error here, in second iteration:         free(current);         current = next;     }     free(set);     set = null; } 

you did 1 malloc() set->points, should 1 free().

you're trying free each point.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -