int main(int argc, char *argv[])
{
printf("successfully started main\n");
struct uf_list myList;
uf_list_allocate(&myList);
printf("successfully allocated myList\n");
insert_node(&myList, 'c');
printf("successfully inserted into myList\n");
return 0;
}
...
void uf_list_allocate(struct uf_list *list)
{
list = malloc(sizeof(struct uf_list));
if(list == NULL)
{fprintf(stderr, "no memory for allocate");}
list->head = list->tail = NULL;
}
//--------------------------------------------------------------------------------------
void insert_node(struct uf_list *list, const char label)
{
struct uf_node *it = malloc(sizeof(struct uf_node));
if(it == NULL)
{fprintf(stderr, "no memory for insert");}
it->c = label;
it->next = NULL;
it->rep = NULL;
if(list->head == NULL) //the list is empty
{ list->head = list->tail = it;}
else
{ list->tail->next = it; list->tail = it; }
it->rep = list->head;
}
/*----------------------------------------------------------------------------*/
struct uf_node
{
char c;
struct uf_node *next;
struct uf_node *rep;
};
/*----------------------------------------------------------------------------*/
struct uf_list
{
struct uf_node *head;
struct uf_node *tail;
};
I am getting a segmentation fault once I try to insert an element into my list from main
.
What is causing the segmentation fault? If you need any more information such as the definitions of the structs
let me know!
EDIT: I realize what I did. Inside allocate
I changed the address of local variable list.
This means that nothing has happened to myList
. However, now I have the following puzzle: I placed the declaration of myList
outside of main,
and everything works:
struct uf_list myList;
int main(int argc, char *argv[])
{
printf("successfully started main\n");
uf_list_allocate(&myList);
printf("successfully allocated myList\n");
insert_node(&myList, 'c');
insert_node(&myList, 'd');
insert_node(&myList, 'e');
printf("successfully inserted into myList\n");
print_uf_list(&myList);
return 0;
}
I can't quite figure out why. It appears that the same logic should apply, namely, since I pass the address of myList
into allocate but then change the local variable list
address and operate on that address, how is this being reflected on myList
whose memory address is not being operated on?