简体   繁体   中英

Cout giving a weird output

This is for a lab I have done, which is to create a simple queue using C++.

#include "Task5.h"
#include <iostream>
using namespace std;

void push(const long &i, node* &n) {
    if (n == NULL) {
        node *ptr = new node;
        ptr -> item = i;
        ptr -> next = NULL;
        n = ptr;
        cout << "Created New Node." << endl;
    }
    else {
        node *ptr = n;
        cout << "Created Pointer" << endl;
        while (ptr -> next != NULL){
            cout << "Finding Next..." << endl;
            ptr = ptr -> next;
        }
        cout << "I'm here." << endl;
        node *temp = new node;
        temp -> item = i;
        ptr -> next = temp;
        cout << "Node Created." << endl;
    }
}

long pop(node* &n) {
    if (n == NULL) cout << "HEY!!! Can't pop an empty queue." << endl;
    else {
        long val;
        node *ptr = n;
        n = n -> next;
        val = ptr -> item;
        delete ptr;
        return val;
    }
}

int main() {
    node *head = NULL;
    push(13,head);
    push(10,head);
    push(18,head);
    push(22,head);
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
    cout << pop(head) << endl;
}

This is giving the following output:

 Created New Node. Created Pointer I'm Here. Node Created. Created Pointer Finding Next... I'm here. Node Created. Created Pointer Finding Next... Finding Next... I'm here. Node Created. 13 10 18 22 HEY!!! Can't pop an empty queue. 6296192 HEY!!! Can't pop an empty queue. 6296192 

So the end result is that the code works, HOWEVER it outputs 6296192 randomly. I thought maybe I misspell something or cout is converting endl; to hex. My lab instructor also has no idea what's happening. Can someone tell me what is happening? If it helps, I am running this code via Linux-run terminal.

Thanks in advance.

In your function:

long pop(node* &n) {

you don't return anything in case of n == NULL is true. So this is UB, and might also cause such random values in output.

I'd suggest using the debugger with a breakpoint on the first cout << pop(head) << endl; and watch the value returned from pop each time.

Also the compiler is probably giving you a warning about the cause of the issue, always pay attention to the warnings it usually means something unintended will happen.

The cout << pop(head) << endl; uses the value returned by pop() but in the case of an empty queue there is no value returned, resulting in undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM