I am creating a Linked List Queue of a struct type. The problem is when I enQueue an object and print the Linked List it displays fine. Enqueueing another item and THEN printing gives me garble. I used GDB and found the variables are getting changed to a bunch of garble and I anticipate that this is due to undefined behavior but I'm having trouble figuring out what I need to do to FIX this problem.
Here's where the variables are defined by the user
printf("First name of employee?\n");
char firstName[MAX_LENGTH];
scanf(" %s", &firstName);
printf("Last name?\n");
char lastName[MAX_LENGTH];
scanf(" %s", &lastName);
if(head->next == NULL) //if there is currently no employee in the list
head->next = hireEmployee(head, lastName, firstName, employeeCount);
else
{
Employee *tmp;
head->next = tmp;
while(tmp->next != NULL)
{
tmp = tmp->next;
}
hireEmployee(tmp, lastName, firstName, employeeCount);
}
Here is part of the enQueue operation.
Employee *new = malloc(sizeof(Employee));
strcpy(new->lastName, lastName);
strcpy(new->firstName, firstName);
And finally here is my print method.
Employee *tmp;
tmp = head->next;
if(head->next == NULL)
printf("Nothing in this list.");
else
{
printf("%s, %s\nEmployee Number: %i\n", tmp->lastName, tmp->firstName, tmp->employeeNumber);
while(tmp->next != NULL)
{
printf("%s, %s\nEmployee Number: %i\n", tmp->lastName, tmp->firstName, tmp->employeeNumber);
tmp = tmp->next;
}
}
What do I need to be doing to fix this? I have ideas of where the undefined behavior may be occurring but NO idea what I should be doing instead.