Hi folks,
Having some frustrating issues trying to free memory from a dynamically allocated array of pointers to linked lists. I think the problem is in how I initialize the pointers to NULL. Is there a more elegant way to have the program recognize that the list is empty so it knows to create a head node for the linked list in the function 'add_end_stub_to_array'?
I ran the code through Valgrind and it says that memory is definitely lost from this array. Any help would be greatly appreciated.
Thanks!
This is the structure definition.
Code:
struct stub_edge {
int loc_id;
int anim_type;
int mkt;
struct stub_edge *next_node;
};
Here is the code snippet from main allocating and deallocating memory to the array.
Code:
struct stub_edge **stub_list = (struct stub_edge **)malloc( sizeof(struct stub_edge *) * 12);
for (i = 0; i < 12; i++)
{
stub_list[i] = (struct stub_edge *)malloc(sizeof(struct stub_edge));
stub_list[i] = NULL;
}
stub_list = add_end_stub_to_array(end_stubs, stub_list);
destroy_end_stub_array(stub_list);
Here the function for adding nodes to the lists by reading through a dynamically allocated 2D array. (The end_stubs array is ordered by month and each linked list represents events occuring within the month).
Code:
struct stub_edge **add_end_stub_to_array(int **end_stubs, struct stub_edge **list)
{
long int i = 0;
int mon = 0;
struct stub_edge *current_node1;
struct stub_edge *new_node1;
int break1 = 0;
while(i < num_edges && break1 == 0 && mon < 12)
{
current_node1 = list[mon];
if(current_node1 == NULL && end_stubs[i][1] == mon)
{
current_node1 = (struct stub_edge*)malloc(sizeof( struct stub_edge ));
current_node1 -> loc_id = end_stubs[i][0];
current_node1 -> anim_type = end_stubs[i][2];
current_node1 -> mkt = end_stubs[i][5];
current_node1 -> next_node = NULL;
i = i + 1;
list[mon] = current_node1;
}
while( end_stubs[i][1] == mon && break1 == 0 )
{
new_node1 = (struct stub_edge*)malloc(sizeof( struct stub_edge ));
new_node1 -> loc_id = end_stubs[i][0];
new_node1 -> anim_type = end_stubs[i][2];
new_node1 -> mkt = end_stubs[i][5];
new_node1 -> next_node = NULL;
current_node1 -> next_node = new_node1;
current_node1 = new_node1;
i = i + 1;
if(i == num_edges)
{
break1 = 1;
i = 0;
}
}
mon = mon + 1;
}
return(list);
}
Here is the function for freeing memory from the list.
Code:
void destroy_end_stub_array(struct stub_edge **list)
{
if(list != NULL)
{
int mon = 0;
struct stub_edge *current_node1;
struct stub_edge *new_node1;
for(mon = 0; mon < 12; mon++)
{
current_node1 = list[mon];
while(current_node1 != NULL)
{
new_node1 = current_node1 -> next_node;
free(current_node1);
current_node1 = new_node1;
}
free(list[mon]);
}
}