1

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.

1 Answer 1

2

This part is a problem:

Employee *tmp;

At this point tmp is a pointer whose contents are undefined.

head->next = tmp;

Now you just stored the undefined contents into head-> next.

while(tmp->next != NULL)

And now you just dereferenced your undefined pointer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.