R
richard
I wrote this code to create and store some structs. This code occasionally blows
up in FreeItem, and I can't figure out why. I only see problems with very large
amounts of data, and then only rarely, making it harder to debug. Do you see
any flaws or have any suggestions for improving the routines?
I declare a data structure:
typedef struct {
char this[256];
int that;
} Item; // this is just an example, usually item is more complex
and another struct to hold these structs:
typedef struct {
int entries;
Item **item;
} List;
before first use:
List list;
list.entries = 0;
list.item = NULL;
We add items to the list with:
void AddItem(List *d, Item *item) {
if( (d->item = (Item **)realloc(d->item, (d->entries+1)*sizeof(*d->item))) ==
NULL) {
printf("AddItem: couldn't reallocate memory for entry %d\n", d->entries);
exit(1);
}
if( (d->item[d->entries] = (Item *)malloc(sizeof(*item))) == NULL) {
printf("AddItem: couldn't allocate memory for entry %d\n", d->entries);
exit(1);
}
memcpy(d->item[d->entries++], item, sizeof(*item));
} // AddItem
And when done, call this to free
void FreeList(List *d) {
int i;
for(i = 0; i < d->entries; i++)
free(d->item);
free(d); // this line is sometimes the source of memory errors
}
up in FreeItem, and I can't figure out why. I only see problems with very large
amounts of data, and then only rarely, making it harder to debug. Do you see
any flaws or have any suggestions for improving the routines?
I declare a data structure:
typedef struct {
char this[256];
int that;
} Item; // this is just an example, usually item is more complex
and another struct to hold these structs:
typedef struct {
int entries;
Item **item;
} List;
before first use:
List list;
list.entries = 0;
list.item = NULL;
We add items to the list with:
void AddItem(List *d, Item *item) {
if( (d->item = (Item **)realloc(d->item, (d->entries+1)*sizeof(*d->item))) ==
NULL) {
printf("AddItem: couldn't reallocate memory for entry %d\n", d->entries);
exit(1);
}
if( (d->item[d->entries] = (Item *)malloc(sizeof(*item))) == NULL) {
printf("AddItem: couldn't allocate memory for entry %d\n", d->entries);
exit(1);
}
memcpy(d->item[d->entries++], item, sizeof(*item));
} // AddItem
And when done, call this to free
void FreeList(List *d) {
int i;
for(i = 0; i < d->entries; i++)
free(d->item);
free(d); // this line is sometimes the source of memory errors
}