Implementation of Queue using Arrays in C++ - c++

I have written this code and am confused about why is it showing segmentation fault. I think my dynamic memory allocation is causing problems for me here. Can anyone tell me what is causing the segmentation fault in here and how to improve the code.
Also, please tell me if I can create the object with the ClassName obj(); and store it in the stack instead of the heap. Or would this implementation be needed in some problems
#include<bits/stdc++.h>
using namespace std;
class Queue
{
public:
int rear, front, size,capacity;
int* arr;
Queue(int c)
{
capacity=c;
rear=c-1;
front=0;
int *arr= new int[c*sizeof(int)];
}
};
int isEmpty(Queue* queue)
{
return (queue->size==0);
}
int isFull(Queue* queue)
{
return (queue->size==queue->capacity);
}
void enqueue(Queue* queue, int x)
{
if(isFull(queue))
return;
queue->rear=(queue->rear+1)%queue->capacity;
queue->arr[queue->rear]=x;
queue->size+=1;
}
int dequeue (Queue* queue)
{
if(isEmpty(queue))
return 0;
int x = queue->arr[queue->front];
queue->front= (queue->front+1)%queue->capacity;
queue->size-=1;
}
int front (Queue* queue)
{
if(isEmpty(queue))
return 0;
return queue->arr[queue->front];
}
int rear (Queue* queue)
{
if(isEmpty(queue))
return INT_MIN;
return queue->arr[queue->rear];
}
int main()
{
Queue* queue=new Queue();
enqueue(queue,10);
enqueue(queue,20);
enqueue(queue,30);
enqueue(queue,40);
cout << "Front item is "
<< front(queue) << endl;
cout << "Rear item is "
<< rear(queue) << endl;
}

Your code have at least 3 problems:
Firstly,
Queue* queue=new Queue();
will lead to compilation error because no default constructor is defined and another constructor is defined in the class Queue.
To fix this, you should do one of:
Change this line to match the defined constructor like Queue* queue=new Queue(1024);
Add default constructor to the class Queue
Add default value of the argument c for the constructor of the class Queue like Queue(int c = 1024)
Secondly, the function dequeue have an execution path in which the execution reach at end of funciton without executing any return statement.
It seems return x; should be added at end of the function.
Thirdly, the line
int *arr= new int[c*sizeof(int)];
is bad because:
This stores the pointer to local variable that will vanish at end of this constructor instead of the member variable.
You don't need to multiply sizeof(int) because what to specify is the number of elements to allocate, not number of bytes.
The line should be
arr= new int[c];

Related

How to avoid a destructor being called twice in C++?

I'm testing out a class representing an dynamic array data structure I made for myself as practice with the language, but I ran into a problem where the destructor is called twice over, causing a heap corruption error.
So far, I have attempted to comment out some of the delete words. However, this leads to undefined behavior.
#include <iostream>
#include "windows.h"
#include <vector>
template<typename T> class Spider {
private:
T** pointer;
int maxSize;
int lengthFilled;
public:
//default constructor
Spider()
{
pointer = new T * [1];
maxSize = 1;
lengthFilled = 0;
}
//destructor
~Spider()
{
for (int i = 0; i < lengthFilled; i++)
{
pop();
}
delete[] pointer;
}
//Pushes an object in
void push(T thing)
{
if (lengthFilled == maxSize)
{
increaseSize();
}
T* thinggummy = &thing;
//then save its pointer in the functional array
pointer[lengthFilled] = thinggummy;
lengthFilled++;
}
//pops the array
void pop()
{
delete pointer[lengthFilled-1];
setSize(lengthFilled - 1);
lengthFilled--;
}
}
int main()
{
Spider<Spider<int>> test((long long)1);
for (int i = 0; i < 2; i++)
{
test.push(Spider<int>());
test.get(i).push(2);//this is implemented in the actual code, just omitted here
std::cout << test.get(i).get(0);
std::cout << "push complete\n";
}
system("pause");
return 0;
}
The expected results for this program should be:
2
push complete
2
push complete
Press any key to continue...
Instead, I get an critical error code in the debug log of "Critical error detected c0000374".
There are two issues here:
Like WhiteSword already mentioned, you are taking the address of a local variable when you do T *thinggummy = &thing. That is going to cause trouble since that address will be invalid as soon as you leave scope (unless maybe T resolves to a reference type).
You call delete on the things in the pointer array. However, these were not allocated via new. Instead they are just addresses of something. So you are trying to free something that was never allocted.

Memory allocation In Tree

Hello everyone i wish you are having a great day, i have a problem with allocation memory for my tree with some code i think it's easier to explain and understand.
#define H 7
class Node{
public:
int node_number;
int depth;
int value;
Node* nodes[L];
public:
Node new_node(int node_number,int depth,int value);
void add_node(Node root_node,Node new_node);
void print_node(Node print_node);
};
To create a node my function is here
Node Node::new_node(int node_number,int depth,int value){
Node x;
x.node_number=node_number;
x.depth=depth;
x.value=value;
x.nodes[L]=(Node*) std::malloc(L*sizeof(Node));
return x;
}
and now when i want to add nodes in the node him self like declared in the class i got Segmentation fault (core dumped)
void Node::add_node(Node root_node,Node new_node){
root_node.nodes[0]=&(new_node);
}
My main function
Node root_node;
root_node=root_node.new_node(10,2,23);
Node x;
x=x.new_node(17,19,7);
root_node.add_node(root_node,x);
root_node.print_node(root_node);
Thank you so much
There are few problems here. Firstly you're not actually allocating any new memory. The line in the new_node method
Node x;
is a local variable so it will be destroyed when the method completes, the method then returns a copy of this object on the stack.
Then in the add_node method there is another problem:
root_node.nodes[0]=&(new_node);
This line doesn't call the node_node method, it actually takes the address of the function. Even if it did call the method it would be returning a copy of the object on the stack not a pointer to an object on the heap which is what you need.
Your code doesn't show the definition of L, I'm going to assume that it is a macro definition. Your new_node method should look like this, node the new reserved word, this is where the new object is created on the heap:
Node* Node::new_node(int node_number,int depth,int value){
Node *x = new Node;
x->node_number=node_number;
x->depth=depth;
x->value=value;
// x->nodes[L]=(Node*) std::malloc(L*sizeof(Node));
// not needed if L is a macro and needs correcting if L is a variable
return x;
}
Now this method returns a pointer to a new object on the heap.
Your add_node method will then look like this:
void Node::add_node(Node root_node,Node new_node){
root_node.nodes[0]=new_node(/* Need to add params here! */);
}
However there is a much better way of doing what you want here. You should write a constructor for the Node class like below:
Node::Node(int node_number,int depth,int value)
{
this->node_number = node_number;
this->depth = depth;
this->value = value;
}
This removes the need for the new_node method and means your add_node method will look like this:
void Node::add_node(Node root_node,Node new_node){
root_node.nodes[0]=new Node(/* Need to add params here! */);
}
Hope this helps.
Although there is already a complete answer provided by PeteBlackerThe3rd, I deem it worthy to also provide an answer that does not use any manual memory allocation as this is often the preferred way in C++.
I took the liberty to make some minor adjustments, e.g., when adding a node it is not necessary to provide the depth in the tree as this can be derived from its parent's node.
The struct uses a std::vector which has (at least) two benefits compared to the code provided in the question. First, there is no need to know the maximum number of children nodes during compile time. If you want to fix this during compile time one can easily replace the std::vector by std::array. Second, there is no need to manually free memory at destruction as this is all taken care of by std::vector.
#include <iomanip>
#include <vector>
struct Node
{
// I expect these data members to be constants
int const d_nodeNumber;
int const d_depth;
int const d_value;
std::vector<Node> d_childNodes;
Node() = delete;
Node(int number, int depth, int value)
:
d_nodeNumber (number),
d_depth (depth),
d_value (value),
d_childNodes ()
{ }
/*
* Note that this function does not ask for a 'depth' argument
* As the depth of a child is always the depth of its parent + 1
*/
void addChildNode (int number, int value)
{
d_childNodes.emplace_back(number, d_depth + 1, value);
}
/*
* Just an arbitrarily function to generate some output
*/
void showTreeFromHere() const
{
int const n = 1 + 2 * d_depth;
std::cout << std::setw(n) << ' '
<< std::setw(5) << d_nodeNumber
<< std::setw(5) << d_depth
<< std::setw(5) << d_value << std::endl;
for (Node const &n: d_childNodes)
n.showTreeFromHere();
}
};
The struct can be used as follows:
int main()
{
Node root_node(0,0,0);
// Add two child nodes
root_node.addChildNode(1,1);
root_node.addChildNode(2,1);
// Add six grandchildren
root_node.d_childNodes[0].addChildNode(3,8);
root_node.d_childNodes[0].addChildNode(4,8);
root_node.d_childNodes[0].addChildNode(5,8);
root_node.d_childNodes[1].addChildNode(6,8);
root_node.d_childNodes[1].addChildNode(7,8);
root_node.d_childNodes[1].addChildNode(8,8);
root_node.showTreeFromHere();
}

Implementation of stack using vectors in c++

#include<iostream>
#include<vector>
using namespace std;
class Stack {
private:
int maxSize;
vector<int> v;
int top;
public:
Stack(int size) {
this->maxSize = size;
this->v.reserve(this->maxSize);
this->top = -1;
}
void push(int j) {
if (!(this->isFull())) {
this->v[++this->top] = j;
} else {
cout << "stack is full"<<endl;
}
}
int pop() {
if (!(this->isEmpty())) {
return this->v[this->top--];
} else {
cout << "\nstack is empty"<<endl;
cout<< "StackOverflow "<<endl;
}
}
int peak() {
return this->v[this->top];
}
bool isEmpty() {
return (this->top == -1);
}
bool isFull() {
return (this->top == this->maxSize - 1);
}
};
int main() {
Stack s(10);
s.push(10);
s.push(20);
cout<<s.pop();
cout<<"\n"<<s.pop();
s.push(40);
cout<<"\n"<<s.pop();
}
How can I make this code more better and reliable for these reasons:
The output of this code is 20 10 40 .
But in the output I want to print "Stack is empty" after every
time the stack is empty after popping out all the elements from the
stack
It fails toprint "Stackis Empty " every time .
You have UB in your code:
this->v[++this->top] = j;
return this->v[this->top--];
ans so on. The fact that you reserved space in a std::vector does not make accessing thous elements legal, you access elements out of bounds. And you overcomplicated your code - std::vector maintains it's size so you do not need index top at all. All you need is push_back() adding element and use back() to access last and then pop_back() to remove it. You can use std::vector>::empty()or std::vector::size() to check if there are elements left.
The specific problem in your code is due to your attempting out of bounds access with a std::vector; the behaviour of which is undefined. Note that reserve does not make that number of elements available for use; only potentially available without a subsequent memory reallocation. If you had used at rather than [] then your C++ standard library would have thrown a runtime error.
std::vector has push_back and a pop_back functions which does allow you to use it to model a stack reasonably effectively.
But, typedef std::stack<int> Stack; in place of all your code is by far the best way.
Don't use C++ standard library container objects to model other containers that are also in the C++ standard library. Container objects are really difficult to write properly; and take a lot of debugging.
The way you programmed it, it only prints "Stack is empty" if the stack is already empty when you call pop, not when it has 1 element and is only empty after calling pop.
Suppose you have 1 element on the stack. So top is 0.
int pop() {
if (!(this->isEmpty())) {
This if evaluatetes to true, and therefore nothing will be printed. This is because isEmpty() evaluates to false with top set to 0.
What you want to do is doing the pop first, and then checking if the stack is empty. On top of checking it at the beginning either way, because you can't pop an empty stack.

Array-style Linked list implementation C++

I am given a task to simulate a linked list structure, but using an array of Nodes rather than an actual linked list. When I call my append function, I want to check to see if my existing array is full, and if it is, I want to double the array size, and append my Node to the end of the "list" (array).
I am having trouble doubling my array size.
To give you context, here is my some of my .h file:
...
const int NULL_INDEX = -1;
struct Node {
char info;
int next;
};
class LList1 {
private:
Node free [4];
// When more memory is called for, the array will double in size
// returns true if reallocation of memory was successful
bool doubleSize();
.
.
.
}
and here is the part of my .cpp file that tries to double the array size:
bool LList1::doubleSize() {
Node* newArray = new Node[this->length()*2];
memcpy(newArray, free, this->length()*2);
free = newArray;
return true;
}
I also tried using realloc and other functions. I keep having the same problem.
The line
"free = newArray"
keeps giving me this error in XCode: "Array type 'Node[4]' is not assignable"
Please give me some insight into a better way to do this. All solutions online seem to work fine for arrays of ints, but not for my array of Nodes.
Much appreciated.
A couple of things are incorrect in your code:
Your free property is a static array. In your case you need a dynamic one, with proper constructor.
The memcpy command takes the size in bytes, hence you need to multiply by sizeof(Node).
Perhaps it was intended, but the doubleSize() method was private.
Here is a corrected version of the code that compiles and runs:
...
const int NULL_INDEX = -1;
struct Node {
char info;
int next;
};
class LList1 {
public:
LList1();
~LList1();
int getLength();
bool doubleSize();
private:
int length;
Node* free;
// When more memory is called for, the array will double in size
// returns true if reallocation of memory was successful
};
int LList1::getLength() {
return this->length;
}
LList1::LList1() {
this->free = new Node[4]; // Default size
this->length = 4;
}
LList1::~LList1() {
delete []this->free;
}
bool LList1::doubleSize() {
Node* newArray = new Node[this->length*2];
memcpy(newArray, free, this->length * sizeof(Node));
free = newArray;
this->length *= 2;
return true;
}
int main(int, char **) {
LList1 l;
std::cout << "Original length: " << l.getLength() << std::endl;
l.doubleSize();
std::cout << "After doubling length: " << l.getLength() << std::endl;
return 0;
}
You are getting confused between arrays and pointers. Your variable free is a constant pointer which cannot be reassigned. You need to change Node free [4] to Node *free if you want to modify its value.
C/C++ int[] vs int* (pointers vs. array notation). What is the difference?

Pointers in linked list not working as expected

This realization of linked list is broken. Address of nodes[0].next doesn't match the nodes[1] address. So nodes[1].next is NULL (as default value). I added some address printing to the search method. It looks like the nodes[1] wasn't initialized?
#include <iostream>
#include <vector>
using namespace std;
typedef struct Node_T {
int data;
Node_T *next;
} Node;
class LinkedList{
public:
vector<Node> nodes;
LinkedList(){
}
void insert(int data) {
Node temp_node;
temp_node.data = data;
temp_node.next = NULL;
size_t len = nodes.size();
nodes.push_back(temp_node);
if (len > 0) {
nodes[len - 1].next = &nodes[len];
}
}
int search(int val){
if (nodes.empty())
return -1;
Node *node_ptr = &nodes[0];
// Debug
cout << &nodes[1] << "\n";
cout << &nodes[0].next << "\n";
int i = 0;
do {
if (node_ptr->data == val) return i;
i++;
} while((node_ptr = node_ptr->next) != NULL);
return -1;
}
};
int main()
{
LinkedList llist;
llist.insert(1);
llist.insert(2);
llist.insert(3);
llist.insert(4);
llist.insert(5);
cout << llist.search(3) << "\n";
return 0;
}
It shows me: 0x8e6a060 0x8e6a05c -1
When you add elements to a vector, references to (and hence addresses of) vector elements are invalidated. You must therefore not use values such as &nodes[0] or &nodes[len], as they are meaningless.
The point with an exercise like this is to get the hang of the internal structure in a linked list. You have replaced that internal structure with a vector<Node>.
Instead of a vector, the idea is to have a
private:
Node* head;
As you data member.
In your insert function you are supposed to dynamically allocate memory for the Node with
Node* newNodePointer = new Node;
And manipulate the pointer with next and such.
It is worth to point out, that this is fine as an exercise, but your "real" code should use standard library facilities.
First, Your printout is incorrect: this line
cout << &nodes[0].next << "\n";
prints the address of next, rather than printing the next itself. Changing to
cout << nodes[0].next << "\n";
gives the correct printout (demo).
However, the main issue is that you keep pointers to elements of std::vector. These become invalid after the first write, because new storage gets allocated for the growing vector.
You can certainly work around this by reserving sufficient space upfront (call nodes.reserve(1000) from the constructor of your list; demo) but that is merely a hack: you should use new and delete to allocate elements of your linked list manually. That is the whole point of this exercise.
But I still need a container to ensure that nodes will be live as expected?
No, you do not. Your class is a container. By referencing the whole chain of nodes from the head pointer it can ensure that the entire chain is kept "live".