I am Learning Stack Data Structure and Unfortunately in my first code I am getting Stack is Full Run time error due to my less knowledge of Stack I am unable to Trace error in my written code please have a look.
Thanks
#include
using namespace std;
struct Stack
{
int data[15];
int top;
};
void init(Stack &s)
{
s.top=-1;
}
bool isEmpty(Stack s)
{
if(s.top == -1)
return true;
else
return false;
}
bool isFull(Stack s)
{
if(s.top > 14)
{
return true;
}
else
{
return false ;
}
}
void push ( Stack &s,int value)
{
if(isFull(s) == true)
{
cout<<"Oooops Stack is Full :(\n";
}
else
{
s.top++;
s.data[s.top]=value;
}
}
int pop (Stack &s)
{
int removedValue = s.data[s.top];
s.data[s.top]=0;
if(isEmpty(s)== true)
{
cout<<"Ohhh Stack is Empty\n";
}
else
{
s.top--;
return removedValue;
}
}
int top(Stack s)
{
return s.top;
}
int main()
{
Stack items;
cout << "Hello Welcome to Stack!" << endl;
push(items,1);
cout<<pop(items)<<endl;
return 0;
}
ok folks here is the error..
i declared a new stack named Stack in main but didnot initialize it using
void init(Stack &s)
{
s.top=-1;
}
so here is the answer by initializing stack in main()
Stack items;
init(items);
Related
I'm Getting a Segmentation fault here
if((cur->block)!=(cur->next)->block)
I Tried to fix Some on my own but didn't got it correct.
this Program is used to implement Control Flow Analysis it was having some more Segmentation faults which were identified and fixed ,but now. I don't have any alternative to try and edit this code.
struct Listnode
{
char data[50];
int leader,block,u_goto,c_goto;
struct Listnode *next;
char label[10],target[10];
}*temp,*cur,*first=NULL,*last=NULL,*cur1;
FILE *fpr;
void createnode(char code[50])
{
temp=(struct Listnode*) malloc(sizeof(struct Listnode));
strcpy(temp->data,code);
strcpy(temp->label,"\0");
strcpy(temp->target,"\0");
temp->leader=0;
temp->block=0;
temp->u_goto=0;
temp->c_goto=0;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=temp;
}
else
{
last->next=temp;
last=temp;
}
}
void main()
{
char codeline[50];
char c,dup[50],target[10];
char *substring,*token;
int i=0,j=0,block,block1;
fpr= fopen("P10-CFA.txt","r");
while((c=getc(fpr))!=EOF)
{
if(c!='\n')
{
codeline[i]=c;
i++;
}
else
{
codeline[i]='\0';
createnode(codeline);
i=0;
}
}
//create last node
codeline[i]='\0';
createnode(codeline);
fclose(fpr);
// find out leaders,conditional stmts
cur=first;
cur->leader=1;
while(cur!=NULL)
{
substring=strstr((cur->data),"if");
if(substring==NULL)
{
if((strstr((cur->data),"goto"))!=NULL)
{
cur->u_goto=1;
(cur->next)->leader=1;
}
}
else
{
cur->c_goto=1;
(cur->next)->leader=1;
}
substring=strstr((cur->data),":");
if(substring!=NULL)
{
cur->leader=1;
}
substring=strstr((cur->data),"call");
if(substring!=NULL)
{
cur->leader=1;
}
if(strstr(cur->data,"return")!=NULL)
{
cur->leader=1;
(cur->next)->leader=1;
}
cur=cur->next;
//to find labels and targets
cur=first;
while(cur!=NULL)
{
if((cur->u_goto==1)||(cur->c_goto==1))
{
substring=strstr(cur->data,":");
if(substring!=NULL)
{
token=strstr(substring,"L" );
if(token!=NULL)
strcpy(cur->target,token);
else
{
substring=strstr(cur->data,"L");
if(substring!=NULL)
strcpy(cur->target,substring);
}
}
if(strstr(cur->data,":")!=NULL)
{
strcpy(dup,cur->data);
token=strtok(dup,":");
//printf("\ntoken:%s",token);
if(token!=NULL)
strcpy(cur->label,token);
}
cur=cur->next;
//to identify blocks
cur=first;
while(cur!= NULL)
{
cur=cur->next;
if((cur->leader)==1)
{
j++;
cur->block=j;
}
else
cur->block=j;
}
printf("\n\n.....Basic Blocks \n");
cur=first;
j=0;
printf("\nBlock %d:",j);
while(cur!=NULL)
{
if ((cur->block)==j)
{
printf("%s",cur->data);
printf("\n\t");
cur=cur->next;
}
else
j++;
printf("\nBlock %d:",j);
}
}
//to output the control flow from each block
printf ("\t\t.......Control Flow.........\n\n");
cur=first;
i=0;
while(cur!=NULL)
{
if((cur->block)!=(cur->next)->block)
{
block=cur->block;
if(cur->u_goto==1)
{
strcpy(target,cur->target);
cur1=first;
while(cur1!=NULL)
{
if(strcmp(cur1->label,target)==0)
{
block1=cur1->block;
printf("\t\tBlock%d---->Block%dln",block,block1);
}
cur1=cur1->next;
}
}
else if(cur->c_goto==1)
{
strcpy(target,cur->target);
cur1=first;
while(cur1!=NULL)
{
if(strcmp(cur1->label,target)==0)
{
block1=cur1->block;
printf("lt\1Block%d---TRUE--->Block%d---FALSE--->Block%d\n",block,block1,(block+1));
}
cur1=cur1->next;
}
}
else if(strstr(cur->data,"return")==NULL)
{
printf("\t\tBlock%d--->Block%d\n",block,(block+1));
}
else
printf("lt\tBlock%d--->NULL\n",block);
}
cur=cur->next;
}
cur=last;
block= cur->block;
printf("\t\tBlock%d--->NULL",block);
}
}
}
I was solving a question named as. Find First and Last Position of Element in Sorted Array
'''
void bin_search(vector<int>&nums,int target,int l,int h,int &a,int &b)
{
if(l>h)
return;
int mid= l + (h - l) / 2;
if(nums[mid]==target)
{
if(nums[mid-1]==target)
{
bin_search(nums,target,l,mid-1,a,b);
}
else
{
a=mid;
}
if(nums[mid+1]==target)
{
bin_search(nums,target,mid+1,h,a,b);
}
else
{
b=mid;
}
}
else if(nums[mid]<target)
{
bin_search(nums,target,mid+1,h,a,b);
}
else
{
bin_search(nums,target,l,mid-1,a,b);
}
}
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int a=-1;
int b=-1;
int l=0;
int h=nums.size()-1;
bin_search(nums,target,l,h,a,b);
return {a,b};
}
};
'''
this is the code which i submitted but i am getting
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000390 overflowed to 0x60200000038c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_vector.h:1043:34
error i am able to pass all the test cases in my complier and other id but didn't able to solve this bug
please help me thanks in advance
I'm solving one of the algorithms problem from university to implemet queue using stacks.
I've got my logic right i guess but the numbers are getting printed in the form of 12-256, 13-256, 14-256 instead of 12,13,14.
Here's my C++ Code,
#include <iostream>
using namespace std;
class Stack{
private:
int arr[200];
int tos = -1;
public:
bool empty(){
return (tos == -1)?true:false;
}
void push(int element){
arr[++tos] = element;
}
int pop(){
return arr[tos--];
}
void show(){
if(tos == -1){
cout<<"stack empty";
}else{
for(int i=tos;i>0;i--)
cout<<arr[i]<<"\t";
}
}
};
class Queue{
private:
Stack s1,s2;
public:
void enQueue(int x){
//just using s1 to add new elements
s1.push(x);
}
int deQueue(){
if(s1.empty())
throw 'e';
else{
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
cout<<"\nelement to be removed:"<<s2.pop();
if(s2.empty())
throw 'f';
else{
int e;
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
}
}
}
};
int main()
{
try{
Queue q1;
q1.enQueue(12);
q1.enQueue(13);
q1.enQueue(14);
q1.enQueue(15);
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
}catch(char c){
cout<<"\nstack empty!";
}
return 0;
}
I'm basically a Python Guy so i'm not able to figure out what's wrong with this code.
I'm new to C++, so please guide me through this.
Thanks in advance!
deQueue suffers from the following problems.
It doesn't return anything.
It's OK for s2 to be empty after its top has been popped.
Here's an updated version that should work.
int deQueue(){
if(s1.empty())
throw 'e';
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
int ret = s2.pop();
cout<<"\nelement dequeued:"<< ret;
// This is not correct.
// It's OK for s2 to be empty after its top has been popped.
// if(s2.empty())
// throw 'f';
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
return ret;
}
Suggestion for further improvement
Queue does not need two Stack objects as member variables. s2 can be a function local variable in deQueue.
class Queue
{
private:
Stack s;
...
};
If you decide to make that change, you'll have to update enQueue and deQueue accordingly.
In one of my classes at Uni we are creating Binary search trees and inserting data and looking them up. My code make sense in my head and because of this I cannot find the error anywhere. I have spent ages trying to find the error but cannot find it anywhere. The only thing that might be causing an error is that the precompiled headers didn't work when I started so i removed them from my project. The error only occurrs when i try to use the BST.Lookup and choose a key that is on the right subtree.
This is my main cpp file:
// BinarySearchTrees.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "BST.h"
#include <iostream>
#include <fstream>
#include <string>
void ReadFile(BST &Bst)
{
int iKey;
std::string Key;
std::string Data;
std::ifstream testFile("Test.txt");
if (testFile.is_open())
{
while (!testFile.eof())
{
getline(testFile, Key, ' ');
getline(testFile, Data);
iKey = stoi(Key);
Bst.Insert(iKey, Data);
}
}
}
int main()
{
std::string Option;
int Choice;
BST BST;
//ReadFile(BST);
BST.Insert(6, "Oscar");
BST.Insert(20, "Ben");
BST.Insert(99, "James");
BST.Insert(1, "Alex");
while (Option != "exit")
{
std::cout << "If you wish to Lookup a Node, Insert value to find. Enter 'exit' to close" << std::endl;
getline(std::cin, Option);
if (Option == "exit")
break;
else
{
Choice = stoi(Option);
BST.Lookup(Choice);
}
}
return 0;
}
I believe that the readfile code may be incorrect but am unsure.
My Binary Search Tree Class:
#include "BST.h"
struct BST::Node {
Key key;
Item item;
Node* leftChild;
Node* rightChild;
Node(Key, Item);
};
void BST::Insert(Key inputKey, Item inputItem)
{
Node* previousNode = nullptr;
if (root == nullptr)
{
root = new Node(inputKey, inputItem);
}
else
{
InsertRec(inputKey, inputItem, root, previousNode);
}
}
void BST::InsertRec(Key inputKey, Item inputItem, Node* & Current, Node* & previousNode)
{
if (Current != nullptr)
{
previousNode = Current;
}
bool isLeft = false;
if (!isLeaf(Current))
{
if (inputKey > Current->key)
{
isLeft = false;
InsertRec(inputKey, inputItem, Current->rightChild, previousNode);
}
else if (inputKey < Current->key)
{
isLeft = true;
InsertRec(inputKey, inputItem, Current->leftChild, previousNode);
}
else
{
Current->item = inputItem;
}
}
else
{
Current = new Node(inputKey, inputItem);
if (isLeft)
{
previousNode->leftChild = Current;
}
else
{
previousNode->rightChild = Current;
}
}
}
BST::Item* BST::Lookup(Key soughtKey)
{
Item* Item = LookupRec(soughtKey, root);
std::string Display = /*std::to_string(soughtKey) + ": " + */ *Item;
std::cout << Display << std::endl;
return Item;
}
BST::Item* BST::LookupRec(Key soughtKey, Node* currentNode)
{
if (!isLeaf(currentNode))
{
if ((currentNode->key > soughtKey))
{
LookupRec(soughtKey, currentNode->leftChild);
}
else if ((currentNode->key < soughtKey))
{
LookupRec(soughtKey, currentNode->rightChild);
}
else
{
return ¤tNode->item;
}
}
else
{
return nullptr;
}
}
bool BST::isLeaf(Node* n)
{
if (nullptr == n)
{
return true;
}
else
{
return false;
}
}
BST::BST()
{
}
BST::Node::Node(Key K, Item I)
{
key = K;
item = I;
leftChild = nullptr;
rightChild = nullptr;
}
And finally my header file for the binary search tree:
#pragma once
#include "iostream"
#include "string"
class BST
{
public:
using Key = int;
using Item = std::string;
void Insert(Key, Item);
Item* Lookup(Key);
BST();
private:
struct Node;
Node* root = nullptr;
static bool isLeaf(Node*);
static Item* LookupRec(Key, Node*);
static void InsertRec(Key, Item, Node* &, Node* &);
};
Any help would be greatly appreciated. I've been stuck on this for too long and I cannot progress without fixing this first.
The Test.txt file is filled with keys and items that are read and inputted like how I do it manually at the start of my main function, so I dont think the error is the file data.
Thanks in advance
UPDATE: Have finally found the error. The problem was with the bool isLeft in my InsertRec function. The bool was always false due to the recursion so have changed the code to compare previousNode->Key with Current->Key to determine if the child goes left or right
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have implemented hierholzer algorithm to find eulerian path in a graph using two stacks. Below is my implementation. There is some runtime error, will be glad if somebody could help
#include<bits/stdc++.h>
using namespace std;
stack<int> result;
stack<int> temp;
class graph
{
int v;
list<int> *adj;
public:
graph(int v)
{
this->v=v;
adj=new list<int> [v];
}
~graph()
{
delete []adj;
}
void add_edge(int u,int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void remove_edge(int u, int v);
int start_vertex();
void print_euler_path(int u);
bool allvisited();
};
int graph::start_vertex()
{
int u=0;
for(int u=0;u<v;u++)
{
if(adj[u].size() & 1)
break;
}
return u;
}
bool graph::allvisited()
{
for(int i=0;i<v;i++)
{
if(adj[i].size()>0)
{
list<int>::iterator it;
for(it=adj[i].begin();it!=adj[i].end();it++)
{
if(*it!=-1)
return false;
}
}
}
return true;
}
void graph::remove_edge(int u,int v)
{
list<int>::iterator i;
i=find(adj[u].begin(),adj[u].end(),v);
*i=-1;
i=find(adj[v].begin(),adj[v].end(),u);
*i=-1;
}
void graph::print_euler_path(int u)
{
temp.push(u);
list<int>::iterator i;
int flag=0;
if(allvisited())
return;
for(i=adj[u].begin();i!=adj[u].end();i++)
{
if(*i!=-1)
{
cout<<"S";
remove_edge(u,*i);
print_euler_path(*i);
}
}
if(!temp.empty())
{
int k=temp.top();
temp.pop();
result.push(k);
if(!temp.empty())
print_euler_path(temp.top());
}
}
int main()
{
graph g(6);
g.add_edge(0,1);
g.add_edge(1,2);
g.add_edge(2,3);
g.add_edge(3,0);
g.add_edge(5,1);
g.add_edge(5,2);
g.add_edge(4,1);
g.add_edge(4,2);
int u=g.start_vertex();
g.print_euler_path(u);
while(!result.empty())
{
cout<<result.top()<<" ";
result.pop();
}
return 0;
}
For exact logic you can refer http://iampandiyan.blogspot.in/2013/10/c-program-to-find-euler-path-or-euler.html
I don't think that these lines do what you want:
remove_edge(u,*i);
print_euler_path(*i);