Cout giving a weird output - c++

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.

Related

Segmentation errors(core dumped) after deleting pointers

I am trying to make a mask delivery, ordering service code.
The function order will add a new order to order list.
The function output will output the list from newest to oldest order.
The function deliver removes the oldest order.
The following is the code:
#include <iostream>
#include <string>
using namespace std;
struct Mask {
string type;
string customer;
Mask *next;
};
void order(Mask *&head, string type, string customer){
cout << "Ordering " << type << " for " << customer << endl;
Mask *oldHead = head;
head = new Mask;
head->type = type;
head->customer = customer;
head->next = oldHead;
}
void output(Mask *head){
cout << "Outputting order list " << endl;
for (Mask *p = head; p != NULL; p = p->next)
cout << " " << p->type << " for " << p->customer << endl;
}
void deliver(Mask *&head){
if (head->next == NULL){
cout << "Delivering " << head->type;
cout << " for " << head->customer << endl;
delete head;
}
else
deliver(head->next);
}
int main()
{
Mask *head = NULL;
order(head, "3M-N95", "Alice");
order(head, "OxyAir", "Burce");
order(head, "3M-N95", "Cindy");
output(head);
deliver(head);
output(head);
}
Everything runs smoothly, but it says segmentation error(core dumped) at the end. I tried adding this:
if (head->next->next == NULL){
deliver(head->next);
head->next == NULL;
}
But the problem still exists. Any help is appreciated.
I changed deliver to this:
void deliver(Mask *&head){
if (head->next->next == NULL){
cout << "Delivering " << head->next->type;
cout << " for " << head->next->customer << endl;
head->next = head->next->next;
delete head->next;
}
else
deliver(head->next);
}
Apparently, just setting the pointer to NULL does not fix the problem, so I just updated it so that the second last pointer pointed directly to the end.
in "deliver" you force the function to meet the condition if(head->next == NULL)
and then trying to reach head->next->next which is like trying to say null->next (resulting with segmentation fault).
I would recommend traversing to the last "Mask" object with a while loop instead of using all those "if" statements which lead to the same result, or at least change the second if to else if in order to avoid meeting this "if" again.

My dynamically linked queue improperly outputs three return functions when called in the same output stream

For an assignment I was tasked with creating a queue with linked lists. Our professor has given us the test code to insure the program is working properly and for grading. My serve function returns a character. However in the main(), the function is called twice within one cout statement, and it returns the character in incorrect order. The getSize function is also called, however it does not seem to do anything.
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
the display outputs: m a b b. However the cout shows as: a m 4. This should obviously come out as: m a 2.
If i separate the serve and the getSize functions, it works just fine, i.e. cout << q1.serve() << " "; cout << q1.serve() << " "; cout << q1.getSize() << " ";
Below I have posted the code for the linked queue. I imagine I have made a mistake with my node pointers, however I have drawn pictures and re-written the code to no avail.
I also apologize if Ive improperly formatted this as it is my first posting. Thank you.
#include <iostream>
using namespace std;
struct Node {
char data;
Node* next;
};
class Queue {
private:
Node* front, * rear;
int size;
public:
Queue();
void append(char);
char serve();
bool isEmpty();
bool isFull();
int getSize();
void display();
};
Queue::Queue() {
front = rear = nullptr;
size = 0;
}
void Queue::append(char v) {
Node* p = new Node;
p->data = v;
p->next = nullptr;
if (size == 0) {
front = rear = p;
size++;
}
else if (size == 1) {
front->next = p;
rear = p;
size++;
}
else {
rear->next = p;
rear = p;
size++;
}
}
char Queue::serve() {
if (front != nullptr) {
Node* temp = front;
char v = temp->data;
front = front->next;
delete temp;
size--;
return v;
}
}
bool Queue::isEmpty() {
return size == 0;
}
bool Queue::isFull() {
return false;
}
int Queue::getSize() {
return size;
}
void Queue::display() {
Node* runner = front;
while (runner != nullptr) {
cout << runner->data << " ";
runner = runner->next;
}
cout << endl;
}
int main() {
cout << boolalpha;
Queue q1 = Queue();
q1.append('m');
q1.append('a');
q1.append('b');
q1.append('b');
q1.display();
cout << endl << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
cout << q1.serve() << " " << q1.serve() << " " << q1.getSize() << endl;
q1.display();
cout << endl;
/*cout << q1.isEmpty() << " " << q1.isFull() << " " << q1.getSize() << endl;
char a = q1.serve(); char b = q1.serve();
cout << a << " " << b << " " << q1.getSize() << endl;*/
}
I'll give you a big hint: Your output is "a m 4", not "m a 4". The remainder of the answer is below...
.
.
.
.
.
.
(edit: added more explanation)
The cout is running the arguments right to left, because of the associativity of the << operator. So it's getting the size, then getting the first item in the queue, then getting the next one. Even though the operator itself is Left-to-Right, in order to apply them in that order, it's evaluating the arguments right to left.
Think of it this way, while it's required to apply the operators on the left before it applies the ones on the right, it's still evaluating the argument on the right of the operator before it evaluates the one on the left.
This is fundamentally about how the stack works. It's loading the evaluation of the arguments and operators right to left so that it can apply the operators in the reverse order.
Since the operators are all the same precedence, it's pushing the right most operand, then the right most operator, then that' operator's left operand, which is everything to the left.
If your operators are L-R associative, that means that the operands are evaluated R-L before being operated on L-R.
Just do
cout << q1.serve() << " ";
cout << q1.serve() << " ";
cout << q1.getSize() << endl;

segmentation error when using priority queue insert/display functions

I seem to keep get a "Segmentation Error: 11" whenever I run any function(insert and display, unable to tell if delete does it since i can't insert) in the program. I'm not totally sure what it means or where to begin looking to fix it. Any help would be greatly appreciated on where to begin. I understand that it has something to do with the memory and from what I was able to find it could mean that something is taking up too much memory.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "priority_queue.h"
//#include <heap.h>
using namespace std;
struct node{
int priority;
int info;
struct node* link;
};
class PriorityQueue{
private:
node* front;
public:
void Priority_Queue(){
front = 0;
}
void insert(int item, int priority){
node* temp, *q;
temp = new node;
temp->info = item;
temp->priority = priority;
if(front == 0 || priority < front->priority){
temp ->link = front;
front = temp;
}
else{
q = front;
while(q->link != 0 && q->link->priority <= priority)
q = q->link;
temp->link = q->link;
q->link = temp;
}
}
void del(){
node* temp;
if(front == 0)
cout << "Underflow" << endl;
else{
temp = front;
cout << "Delete item is: " << temp->info << endl;
front = front->link;
free(temp);
}
}
void display(){
node* ptr;
ptr = front;
if(front == 0)
cout << "Queue is empty" << endl;
else{
cout << "Queue is: " << endl;
cout << "Priority Item" << endl;
while(ptr != 0){
cout << ptr->priority << endl;
ptr = ptr->link;
}
}
}
};
int main(){
int choice, item, priority;
PriorityQueue pq;
while(1){
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Quit" << endl;
cout << "Enter Choice " << endl;
cin >> choice;
switch(choice){
case 1:
cout << "Input the item value to be added into the queue" << endl;
cin >> item;
cout << "Enter its priority " << endl;
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default:
cout << "That is not an option" << endl;
}
}
//while(choice != 4);
return 0;
}
The problem appears to be the class definition. As WhozCraig points out the name of the presumed constructor is wrong, so it never gets called. The corrected code:
class PriorityQueue {
private:
node* front;
public:
PriorityQueue() : front(nullptr) {
}
};
If you had a look in your debugger you'd probably see that front was never properly initialized. In C++ try and use nullptr to represent a "null pointer". In C use NULL. Using 0 creates a lot of ambiguity even if it "works" for historical reasons.

Visual Studio C++ 2k15 - Getting error on pointer address

this is my first post on Stack Overflow :)
Sorry if I seems egoistic, but I have an exam tomorrow and I'm facing a problem that I cannot solve. Hope to find here an answer, I tried to find out if there was already an opened 3d, but I cannot find it.
Here's my problem:
I'm writing a code in C++, using the pointer. Because of I retrieve always the same error on a larger code, I tried with an easier one, but the error persists.
The code is the following:
#include <iostream>
using namespace std;
struct EXAMPLE {
int value;
EXAMPLE *next;
};
int insertnew(EXAMPLE *&sorting, EXAMPLE val);
int printlist(EXAMPLE *&sorting);
int main() {
int i;
EXAMPLE new;
EXAMPLE *list = NULL;
for (i = 0; i < 3; i++)
{
cout << "value: " << endl;
cin >> new.value;
insertnew(list, new);
}
printlist(list);
system("Pause");
return 0;
}
int insertnew(EXAMPLE *&sorting, EXAMPLE val){
EXAMPLE *temp;
temp = new EXAMPLE;
temp->value = val.value;
temp->next = sorting;
sorting = temp;
return 0;
}
int printlist(EXAMPLE *&sorting) {
while (sorting != 0)
{
sorting = sorting->next;
cout << sorting->next << " " << sorting->value << endl;
}
return 0;
}
It's an easy LIFO structure.
I get a bad reading access error on this line:
cout << elenco->next << " " << elenco->valore << endl;
But here's the curios thing.
If I revert the lines in this way:
int printlist(EXAMPLE *&sorting) {
while (sorting != 0)
{
cout << sorting->next << " " << sorting->value << endl;
sorting = sorting->next;
}
return 0;
}
as a FIFO structure, I got no error at all!
Can you help me understanding where the problem is?
Thanks in advance
//edit
Uops, find out my error.
The while was supposed to be a recursive function, dunno why I inserted a while, assuming it will function as a recursive function.
just solved
cout << lista->value << endl;
while (list != NULL)
{
list = list->next;
if (list != 0) {
cout << list->value << endl;
}
}
Sorry
Let's take a look at your example code:
int printlist(EXAMPLE *&sorting) {
while (sorting != 0) //As long as "sorting" is not null
{
sorting = sorting->next; //Set "sorting" to the next value
cout << sorting->next << " " << sorting->value << endl; //print the value
}
return 0;
}
Just play this code through if you have only one element in your LIFO list.
int printlist(EXAMPLE *&sorting) {
while (sorting != 0) //"sorting" is not null
{
sorting = sorting->next; //Set "sorting" to the next value, which is null
cout << sorting->next << " " << sorting->value << endl; //crash because "sorting" is null
}
return 0;
}
This will happen every time you hit the last element.
You can change your code to a do-while-loop with an additional if, or add an if with a break within your current loop. But I would recommend to go with a for-loop on this one.
Also you don't need to pass the pointer by reference. You even shouldn't do it, as you don't want to change your list when printing it (as your current code does...)
How about something like this:
int printlist(EXAMPLE * sorting) {
for (EXAMPLE * current = sorting; current != 0; current = current->next)
{
cout << current << " " << current->value << " -> " << current->next << endl;
}
return 0;
}
I also changed the output a little bit to show more interesting data.
You are trying to access the tail of the list when sorting->next reaches the last element. With the second code you access only list elements.
Clear, thanks
I also tried another version
int printlist(EXAMPLE *list) {
if (list != NULL)
{
cout << list->value << "-> " << list->next << endl;
printlist(list->next);
}
return 0;
}
and this is how it was supposed to work from the beginning. In this way by just switching the two rows inside the IF I can change from LIFO to FIFO :)

c++ linked list deallocation error: Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

In LinkedList.h I have the following code:
#ifndef LINK_H
#define LINK_H
template<typename T>
struct Node
{
T data;
Node *link;
};
#endif
In my Main.cpp I have the following code:
int size = 1;
int data = 0;
cout << "How big for linked list? ";
cin >> size;
cout << endl;
Node<int> *head;
Node<int> *node = new Node<int>[size];
head = &node[0];
for (int i = 0; i < size; i++)
{
cout << "Input data for link " << i + 1 << ": ";
cin >> node[i].data;
if (i < size - 1)
node[i].link = &node[i + 1];
else
node[i].link = NULL;
}
Node<int> *ptr = head;
cout << "Linked list has current data: ";
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl << endl << "What data do you want to add to the front of the list? ";
cin >> data;
cout << endl;
//add
Node<int> *loc = new Node<int>;
loc->data = data;
loc->link = head;
head = loc;
cout << "Linked list has current data: ";
ptr = head;
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl << endl << "Deleting the data you just added." << endl;
//delete single
Node<int> *temp = new Node<int>;
temp = head;
head = head->link;
delete temp;
cout << "Linked list has current data: ";
ptr = head;
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl;
//delete entire list
ptr = head;
while (ptr)
{
cout << "/";
Node<int> *old = new Node<int>;
old = ptr;
ptr = ptr->link;
delete old;
}
cout << endl;
Upon attempting to deallocate this linked list, I get an error like the one in the title and my program crashes. It seems like c++ is trying to access memory it no longer has access to, and it has something to do with my loc pointer / adding a new link to the front of the list. Can anyone tell me where my code went wrong? The parts that say code removed are basically just couts to print what's in the linked list.
Edit: The error occurs after 2 iterations through the last while loop.
Edit2: It seems after I call the line:
delete temp;
head loses its link and returns garbage. Why?