Question

I am trying to implement a queue in C (using this implementation) where, given an input file with some number of lines each containing 5 values, a struct Item is created for that line and the values are assigned to the struct variables value1...value5. The struct is then placed in a queue, so the first line of the file will be the first struct in the queue, and the last line will be the last struct.

However, I am getting some weird behaviour when trying to read values from the structs in the queue. The end of the code segment below prints value1 and value5 as a debug check to make sure the values are correct. It should print struct1->value1 and struct1->value5 for both head and tail on the first iteration, and then struct1->value1 and struct1->value5 for head and struct2->value1 and struct2->value5 for tail on the second iteration, but instead it prints strange large values for both head and tail. (plus, it seems to forget about the first struct altogether.) What am I doing wrong here?

Sample file:
1 0 10 1 3
2 0 10 10 1
------------
/* read input file */
/* while the current line of the file is not null */
...
    /* create new item */
    Item *newItem = malloc(sizeof(Item));

    /* string tokenizer */
    /* adds tokens from current line to tokens[i] */
    ...

    /* set item variables */
    newItem->value1 = strtol(tokens[0], NULL, 10);  //should contain e.g. 1
    newItem->value2 = strtol(tokens[1], NULL, 10);  //should contain e.g. 0
    newItem->value3 = strtol(tokens[2], NULL, 10);  //should contain e.g. 10
    newItem->value4 = strtol(tokens[3], NULL, 10);  //should contain e.g. 1
    newItem->value5 = strtol(tokens[4], NULL, 10);  //should contain e.g. 3

    /* add to item queue */
    queue_push_tail(itemQueue, &newItem);

    /* check queue values */
    if(!queue_is_empty(itemQueue)) {                        //after two lines,
        Item *itemHead = queue_peek_head(itemQueue);        //this should differ...
        printf("Head: %d %d\n", itemHead->value1, itemHead->value5);
        Item *itemTail = queue_peek_tail(processQueue);     //...from this
        printf("Tail: %d %d\n", itemTail->value1, itemTail->value5);
    }

Expected output:

Head: 1 3   //when first line is read
Tail: 1 3
Head: 1 3   //when second line is read
Tail: 2 1

Actual output:

Head: 146752 -4196581   //when first line is read
Tail: 146752 -4196581
Head: 146792 -4196581   //when second line is read
Tail: 146792 -4196581
Was it helpful?

Solution

This:

queue_push_tail(itemQueue, &newItem);

doesn't look right, it doesn't match how you peek items from the queue. If the queue is storing pointers, hand it newItem, not the address of newItem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top