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;
}
Queue* queue=new Queue();is something you added later and only without you got a segmentation fault. It is not possible to get a segfault with the posted codeQueue?