Fix memory handling for taxonomy data

The way we freed things and cleared out the variables potentially left
dangling data behind and could end up calling free on garbage data,
leading to random crashes.

Signed-off-by: Dirk Hohndel <dirk@hohndel.org>
This commit is contained in:
Dirk Hohndel 2015-07-13 07:09:55 -07:00
parent 15de7f0b71
commit 3478943f2f
4 changed files with 10 additions and 11 deletions

View file

@ -170,9 +170,7 @@ void copy_dive_site(struct dive_site *orig, struct dive_site *copy)
copy->description = copy_string(orig->description); copy->description = copy_string(orig->description);
copy->uuid = orig->uuid; copy->uuid = orig->uuid;
if (orig->taxonomy.category == NULL) { if (orig->taxonomy.category == NULL) {
free_taxonomy(copy->taxonomy.category); free_taxonomy(&copy->taxonomy);
copy->taxonomy.category = NULL;
copy->taxonomy.nr = 0;
} else { } else {
if (copy->taxonomy.category == NULL) if (copy->taxonomy.category == NULL)
copy->taxonomy.category = alloc_taxonomy(); copy->taxonomy.category = alloc_taxonomy();
@ -200,6 +198,5 @@ void clear_dive_site(struct dive_site *ds)
ds->longitude.udeg = 0; ds->longitude.udeg = 0;
ds->uuid = 0; ds->uuid = 0;
ds->taxonomy.nr = 0; ds->taxonomy.nr = 0;
free_taxonomy(ds->taxonomy.category); free_taxonomy(&ds->taxonomy);
ds->taxonomy.category = NULL;
} }

View file

@ -1527,7 +1527,7 @@ static void dive_site_end(void)
if (verbose > 3) if (verbose > 3)
printf("completed dive site uuid %x8 name {%s}\n", ds->uuid, ds->name); printf("completed dive site uuid %x8 name {%s}\n", ds->uuid, ds->name);
} }
free_taxonomy(cur_dive_site->taxonomy.category); free_taxonomy(&cur_dive_site->taxonomy);
free(cur_dive_site); free(cur_dive_site);
cur_dive_site = NULL; cur_dive_site = NULL;
} }

View file

@ -28,11 +28,13 @@ struct taxonomy *alloc_taxonomy()
return calloc(TC_NR_CATEGORIES, sizeof(struct taxonomy)); return calloc(TC_NR_CATEGORIES, sizeof(struct taxonomy));
} }
void free_taxonomy(struct taxonomy *t) void free_taxonomy(struct taxonomy_data *t)
{ {
if (t) { if (t) {
for (int i = 0; i < TC_NR_CATEGORIES; i++) for (int i = 0; i < t->nr; i++)
free((void *)t[i].value); free((void *)t->category[i].value);
free(t); free(t->category);
t->category = NULL;
t->nr = 0;
} }
} }

View file

@ -32,7 +32,7 @@ struct taxonomy_data {
}; };
struct taxonomy *alloc_taxonomy(); struct taxonomy *alloc_taxonomy();
void free_taxonomy(struct taxonomy *t); void free_taxonomy(struct taxonomy_data *t);
#ifdef __cplusplus #ifdef __cplusplus
} }