Because the function returns the link-node itself, not the “payload” that is supposed to be stored in the queue.
Typical queue implementation (singly-linked list)
c
typedef struct queue_object
{
void *data; /* what the user pushed */
struct queue_object *next;
} queue_object;
queue_peek() is meant to give the caller back the data field (the item that was enqueued).
However your code
c
return queueRunning->next; /* <- a queue_object * */
hands back the node (queue_object *), while the function is declared to return void *.
When the caller later treats that pointer as “the stored object” everything is off by one
(pointer size, alignment, wrong address, …) and you will either get garbage or crash.
Fix 1 – return the data that’s inside the node (most common)
c
void *queue_peek(queue_object *queue)
{
if (queue == NULL || queue->next == NULL)
return NULL; /* empty queue */
/* Walk to the last node ------------------------------------------------ */
queue_object *n = queue;
while (n->next != NULL)
n = n->next; /* n now points to last node */
return n->data; /* give caller the payload */
}
Fix 2 – if, for some reason, you really want to return the node,
then change the function’s return type:
c
queue_object *queue_peek(queue_object *queue)
{
if (queue == NULL || queue->next == NULL)
return NULL;
queue_object *n = queue;
while (n->next->next != NULL) /* or while (n->next) … */
n = n->next;
return n->next; /* last node */
}
Choose one of the two approaches, but make sure the return type and the value you
return agree with each other and with what the rest of the program expects.