I'm trying to implement a queue in C++. The queue holds strings.
I'm using the following code:
#include <iostream>
#include <stdlib.h>
struct qnode {
std::string data;//it stores a string
qnode *link;//and has a pointer to the next node in the structure.
};
class queue {
private:
qnode *front; // Pointer to first node.
qnode *rear; // Pointer to last node.
public:
// Constructor.
queue();
//Is the queue empty?
bool empty() ;
//peeks first element
int first(std::string *c);
// Adds element to the queue.
int enqueue(std::string c);
// Extracts an element from the queue.
int dequeue(std::string *c);
// Destructor.
~queue();
};
//////////// ACTUAL CODE /////////////
//Constructor, front and rear initially point to null.
queue::queue() {
front = NULL;
rear = NULL;
}
// If front points to null then the queue is empty.
bool queue::empty() {
return (front == NULL);
}
int queue::first(std::string *c) {
int res = 1;
if (!empty()) {
res = 0;
*c = front->data;
}
return res;
}
//Function for adding an element to the end of queue.
int queue::enqueue (std::string c){
int res = 1;
qnode *tmp; // Auxiliar pointer.
tmp = new qnode; //Auxiliar new node.
if(tmp != NULL) {
// If the queue is empty then we store the data in tmp and make its link point to null and front and rear become tmp.
if(empty()){
tmp->data = c;
tmp->link = NULL;
front = tmp;
rear = tmp;
rear->link = tmp;
} else {
// If it is not, then last node's link point to tmp, we store the data in tmp and tmp's link point to null.
rear->link = tmp;
tmp->data = c;
tmp->link = NULL;
// Rear of the queue points to tmp now.
rear = tmp;
}
res = 0;
}
return res;
}
// Function for extracting an element from the queue.
int queue::dequeue(std::string *c){
int res = 1;
// We make sure queue is not empty and access first node's data with the help of tmp.
if(!empty()) {
qnode *tmp;
tmp = front;
//The data extracted is stored in the character container c, passed by reference.
*c = tmp->data;
// Front now has to point to the next node and the old element has to be deleted.
front = front->link;
delete tmp;
res = 0;
}
return res;
}
// Destructor
queue::~queue() {
// If it is already empty we don't have to do anything.
if (empty()){
return;
}
qnode *tmp;
// We take front element and delete it throught a tmp node till the queue is empty.
while (!empty()){
tmp = front;
front = front->link;
delete tmp;
}
}
//////////// MAIN ///////////
int main(int argc, char *argv[]) {
queue queue;
std::string str2;
queue.enqueue("hello");
queue.dequeue(&str2);
std::cout << str2;
}
Sadly, I get the following error:
$ g++ -o issue issue.cpp $ ./issue issue(23060,0x7fff71058310) malloc: * error for object 0x7f962b403920: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug helloAbort trap: 6
If I comment the queue destructor (the "while" block), the implementation works fine. The implementation also worked fine using char elements (just single letters).
Can anyone enlighten me?