i'm making a program where you can create a linked list and modify/delete/add/print value, but i'm getting some error testing it. First one is segmentation fault 11: when you add the 4th value and there are all equal values (1, 1, 1, 1), trying to print the list will get you a segfault, can't figure it out why. Second error (for the moment): sometimes the 6th or 8th value added will delete all other values, living the last two inserted and placing a 0 in tail.
This is the portion of code interested:
typedef struct list
{
int value;
struct list* next_ptr;
}tylist;
int main()
{
tylist *ptrptr;
ptrptr = NULL;
printf("\nI'm going to initialize the list now\n");
action(choicer(), &ptrptr);
return 0;
}
void insert_at_beg(tylist** ptrptr, int value)
{
if(*ptrptr != NULL)
{
tylist* tmp_ptr;
tmp_ptr = *ptrptr;
*ptrptr = (tylist*)malloc(sizeof(tylist));
(*ptrptr)->value = value;
(*ptrptr)->next_ptr = tmp_ptr;
free(tmp_ptr);
}
else
{
printf("\nList is empty, that's your first entry\n");
*ptrptr = (tylist*)malloc(sizeof(tylist));
(*ptrptr)->value = value;
(*ptrptr)->next_ptr = NULL;
}
void action(int choice, tylist **ptrptr)
{
switch(choice)
{
int value;
case 1:
printf("\nValue: ");
scanf("%d", &value);
insert_at_beg(ptrptr, value);
action(choicer(), ptrptr);
break;
case 8:
visit_list(ptrptr);
action(choicer(), ptrptr);
break;
}
}
void visit_list(tylist **ptrptr)
{
while((*ptrptr) != NULL)
{
printf(" %d", (*ptrptr)->value);
ptrptr = &((*ptrptr)->next_ptr);
}
}
I've deleted some lines of code on purpose, because it seems just long enough this way, if it's unclear i'll post more.
P.s. i'm sorry for my bad english, i'm trying to improve it.