Debug Assertion Error as soon as I take the input. Something wrong with "delete"? - debugging

I am having debug assertion error as soon as I input two elements. The program was giving me access reading or sometimes writing violation error after taking 7-8 entries but after I deleted the dynamic array, it is showing debug assertion failed after taking first two inputs and breaks down. Any idea for how to solve it? I am copying only my air class here. I have similar Fire, earth and water classes too.
The error is BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Someone else too asked this question but i can't figure out My program errors. Kindly help would be appreciated.
#ifndef AIR_H
#define AIR_H
#include <iostream>
#include <string>
#include "element.h"
using namespace std;
class Air :public Element
{
public:
string air;
string Elements [2];
int i;
string *elements;
public:
Air(string n): Element (n)
{
air = n;
i=-1;
elements = new string[2];
}
void alreadyExists (string a)
{
int lineCount = 0;
ifstream read;
read.open ("Air.txt", ios::in | ios::app);
while(!read.eof())
{
string x;
read>>x;
lineCount++;
}
lineCount--;
read.close();
read.open("Air.txt", ios::in|ios::app);
for(int i = 0; i < lineCount; i++)
{
read>>elements[i];
}
bool Found = false;
for(int i = 0; i < lineCount; i++) {
if(a == elements[i])
{
Found = true;
break;
}
}
if(!Found)
{
write2file (a);
}
}
void write2file (string air)
{
ofstream write;
write.open ("Air.txt", ios::out|ios::app);
{
write<<air<<endl;
}
}
void DisplayA ()
{
/*for(int i=0; i<2; i++)//( to read through the arrays )
{
cout<<Elements[i]<<endl;
}*/
ifstream read ("Air.txt", ios::in|ios::app);
int i=0;
while (read >> Elements[i])
{
cout<<Elements[i]<<endl;
}
}
Air operator+(Air & air)
{
Air newElement ("NULL");
if (this->air == "Air"||this->air=="air"&& air.air == "Air"||air.air=="air")
{
newElement.air = "Pressure";
cout<<"Yay!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else if ((this->air == "Air"||this->air == "air") && (air.air == "Pressure"||air.air=="pressure"))/* || ((this->air == "Pressure"||this->air=="pressure") && ( air.air == "Air"||air.air=="air")))*/
{
newElement.air = "Atmosphere";
cout<<"Wuhooo!! You've made: "<<newElement.air<<endl;
alreadyExists (newElement.air);
//PushA (newElement.air);
//write2file (newElement.air);
return newElement;
}
else return newElement;
}//pressure, atmosphere
~ Air ()
{
delete []elements;
}
};
#endif

BLOCK_TYPE_IS_VALID (pHead->nBlockUse)
Assertion means a corrupt heap at deleting/clearing.
As far as I see, you missed the virtual deconstructor of Element.
Try something like:
virtual ~Element() {}
in class Element.
And please post also the Element class.
Good luck!

Related

Why does my code giving me "mismatch in formal parameter list"?

I am trying to transfer the elements from a source stack to a destination stack. And for that i am using some variables and making sure that get transfered into the destination stack in the same order as they were in the source stack. I wrote the following code
#include <iostream>
#include <stack>
using namespace std;
template <typename S>
void transferByVar(stack<S> &source, stack<S> &dest)
{
int var = 0;
S topVal;
if (source.empty())
return;
else if (source.size() == 1)
{
dest.push(source.top());
source.pop();
}
int size = source.size();
while (count != size)
{
topVal = source.top();
source.pop();
while (source.size() != count)
{
dest.push(source.top());
source.pop();
}
source.push(topVal);
while (!dest.empty())
{
source.push(dest.top());
dest.pop();
}
++count;
}
}
int main()
{
stack <int> s1;
stack<int> s2;
s1.push(0);
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
s1.push(6);
s1.push(7);
s1.push(8);
s1.push(9);
transferByVar(s1, s2);
int size = s2.size();
for (int i = 0; i < size; i++)
{
cout << s2.top() << " ";
s2.pop();
}
return 0;
}
but it gives me an error of C2563: mismatch of formal parameter list. What can I do to fix this?

Error in code when searching through the right subtree in my binary search tree

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 &currentNode->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

Infix To postfix Evaluation using stack and array

i am trying to convert infix to postfix but unable to get any output although program is free of error and logically correct. its just showing the value of m. I tried to print hello inside loop , but its unable to print that.I can't understand why its not going inside loop. Can't figure out the exact reason behind it.
#include <bits/stdc++.h>
#define m 21
using namespace std;
int isitoperattor(char c) //to find precdenec of operator
{
if(c=='+'||c=='-')
return 1;
if(c=='*' || c=='/')
return 2;
if(c=='('||c==')')
return 3;
}
void infixtopostfix(char str[m]){
char out[m];
cout<<m<<endl;
stack <char> s;
static int k;
for(int i=0;i<m;i++)
{
cout<<"hello";
if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){
out[k]=str[i];
k++;}
else if (str[i]=='(')
s.push(str[i]);
else if (str[i]==')'){
//int j=i-1;
while(s.top()!='('){
out[k]=s.top();
s.pop();
k++;
//-;
}
s.pop();
}
else
{
if(isitoperattor(str[i]) && (isitoperattor(str[i])<isitoperattor(s.top()))){
while(isitoperattor(s.top())>=isitoperattor(str[i])){
out[k]=s.top();
s.pop();
k++;
}
}
}
s.push(str[i]);
}
}
while(!s.empty())
{
out[k]=s.top();
s.pop();
k++;
}
//string out;
for(int j=0;j<k;j++)
cout<<out[j];
}
int main()
{
char str[m]="a+b*(c^d-e)^(f+g*h)-i";
infixtopostfix(str);
return 0;
}

IndexOutOfBoundsException when I attempt to use list.contain(...), not sure how to fix

public static void main(String[] args) {
List<String> stuff = new ArrayList<String>();
List<String> fc = new ArrayList<String>();
List<String> on = new ArrayList<String>();
List<String> done = new ArrayList<String>();
int d=0;
int x=0;
int r=0;
//"inputs" is an array with all the inputs from the user.
//You will have to go through and extract the data from "inputs" and store it in
//a data type that works
Scanner in = new Scanner(System.in);
int inputs_size = 0;
inputs_size = 100;
String[] inputs = new String[inputs_size];
for(int i = 0; i < inputs_size; i++) {
String inputs_item;
try {
inputs_item = in.nextLine();
} catch (Exception e) {
inputs_item = null;
}
inputs[i] = inputs_item;
}
for(int n=0; n<inputs.length-1; n++){
if(inputs[n]==null){
break;
}
stuff.add(inputs[n]);
}
while(d<stuff.size()){
if(stuff.get(d).equals("0")){
x++;
}
d++;
}
for(int t=0; t<stuff.size(); t++){
if(stuff.get(t).equals("0")){
break;
}
fc.add(stuff.get(t));
}
r=fc.size();
while(r<stuff.size()-1){
if(stuff.get(r).equals("0")){
r++;
x=x-1;
}
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
if(x==3 && stuff.get(r)!="0"){
tw.add(stuff.get(r));
}
if(x==2 && stuff.get(r)!="0"){
th.add(stuff.get(r));
}
if(x==1 && stuff.get(r)!="0"){
fo.add(stuff.get(r));
}
if(x==0 && stuff.get(r)!="0"){
fi.add(stuff.get(r));
}
if(x==-1 && stuff.get(r)!="0"){
si.add(stuff.get(r));
}
r++;
}
int z=0;
int counter = 1;
for(; counter < fc.size(); counter++) {
if(counter>fc.size()){
break;
}
**if(fc.contains(on.get(counter)))** {
z=0;
}
else{
z=1;
break;
}
}
if(z==0){
done.add(on.get(0));
}
counter=1;
z=0;
System.out.println(done);
}
}
I am getting an IndexOutOfBounds error for the line of code with the asterisks around it (fc.contains(...)). I am attempting to create a program that acts as a fridge, receives input and determines what recipes I am capable of making.
Example input:
(milk
cheese
eggs
honey) -ingredients in fridge
(0) -separates lists
(eggs and honey) -recipe in question
(eggs
honey) -ingredients required for recipe, are they in fridge?? yes
So my output would be: Eggs and Honey, or the names of the recipes I can make.
Where did I go wrong here? Thank you!
Following your code, I think your on array is null.
Look:
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
It is the only time you try to add something to your on. And your fc and stuff size will be the same, since you doesn't have something to make it different (instead of this .equals("0"), but if you enter anything else, it will be the same). After that, we have:
r=fc.size();
while(r<stuff.size()-1){
We know that fc and stuff have the same size, then r won't be lower than stuff.size()-1.
By not entering the loop, it will remains null. So any .get() will result in IndexOutOfBounds.

Looking at Sorts - Quicksort Iterative?

I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up.
I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?
I'll try to give a more general answer in addition to the actual implementations given in the other posts.
Is it possible and, if so, how?
Let us first of all take a look at what can be meant by making a recursive algorithm iterative.
For example, we want to have some function sum(n) that sums up the numbers from 0 to n.
Surely, this is
sum(n) =
if n = 0
then return 0
else return n + sum(n - 1)
As we try to compute something like sum(100000), we'll soon see this recursive algorithm has it's limits - a stack overflow will occur.
So, as a solution, we use an iterative algorithm to solve the same problem.
sum(n) =
s <- 0
for i in 0..n do
s <- s + i
return s
However, it's important to note that this implementation is an entirely different algorithm than the recursive sum above. We didn't in some way modify the original one to obtain the iterative version, we basically just found a non-recursive algorithm - with different and arguably better performance characteristics - that solves the same problem.
This is the first aspect of making an algorithm iterative: Finding a different, iterative algorithm that solves the same problem.
In some cases, there simply might not be such an iterative version.
The second one however is applicable to every recursive algorithm. You can turn any recursion into iteration by explicitly introducing the stack the recursion uses implicitly. Now this algorithm will have the exact same characteristics as the original one - and the stack will grow with O(n) like in the recursive version. It won't that easily overflow since it uses conventional memory instead of the call stack, and its iterative, but it's still the same algorithm.
As to quick sort: There is no different formulation what works without storing the data needed for recursion. But of course you can use an explicit stack for them like Ehsan showed. Thus you can - as always - produce an iterative version.
#include <stdio.h>
#include <conio.h>
#define MAXELT 100
#define INFINITY 32760 // numbers in list should not exceed
// this. change the value to suit your
// needs
#define SMALLSIZE 10 // not less than 3
#define STACKSIZE 100 // should be ceiling(lg(MAXSIZE)+1)
int list[MAXELT+1]; // one extra, to hold INFINITY
struct { // stack element.
int a,b;
} stack[STACKSIZE];
int top=-1; // initialise stack
int main() // overhead!
{
int i=-1,j,n;
char t[10];
void quicksort(int);
do {
if (i!=-1)
list[i++]=n;
else
i++;
printf("Enter the numbers <End by #>: ");
fflush(stdin);
scanf("%[^\n]",t);
if (sscanf(t,"%d",&n)<1)
break;
} while (1);
quicksort(i-1);
printf("\nThe list obtained is ");
for (j=0;j<i;j++)
printf("\n %d",list[j]);
printf("\n\nProgram over.");
getch();
return 0; // successful termination.
}
void interchange(int *x,int *y) // swap
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
void split(int first,int last,int *splitpoint)
{
int x,i,j,s,g;
// here, atleast three elements are needed
if (list[first]<list[(first+last)/2]) { // find median
s=first;
g=(first+last)/2;
}
else {
g=first;
s=(first+last)/2;
}
if (list[last]<=list[s])
x=s;
else if (list[last]<=list[g])
x=last;
else
x=g;
interchange(&list[x],&list[first]); // swap the split-point element
// with the first
x=list[first];
i=first+1; // initialise
j=last+1;
while (i<j) {
do { // find j
j--;
} while (list[j]>x);
do {
i++; // find i
} while (list[i]<x);
interchange(&list[i],&list[j]); // swap
}
interchange(&list[i],&list[j]); // undo the extra swap
interchange(&list[first],&list[j]); // bring the split-point
// element to the first
*splitpoint=j;
}
void push(int a,int b) // push
{
top++;
stack[top].a=a;
stack[top].b=b;
}
void pop(int *a,int *b) // pop
{
*a=stack[top].a;
*b=stack[top].b;
top--;
}
void insertion_sort(int first,int last)
{
int i,j,c;
for (i=first;i<=last;i++) {
j=list[i];
c=i;
while ((list[c-1]>j)&&(c>first)) {
list[c]=list[c-1];
c--;
}
list[c]=j;
}
}
void quicksort(int n)
{
int first,last,splitpoint;
push(0,n);
while (top!=-1) {
pop(&first,&last);
for (;;) {
if (last-first>SMALLSIZE) {
// find the larger sub-list
split(first,last,&splitpoint);
// push the smaller list
if (last-splitpoint<splitpoint-first) {
push(first,splitpoint-1);
first=splitpoint+1;
}
else {
push(splitpoint+1,last);
last=splitpoint-1;
}
}
else { // sort the smaller sub-lists
// through insertion sort
insertion_sort(first,last);
break;
}
}
} // iterate for larger list
}
// End of code.
taken from here
I was unable to find a reliable method of doing a quicksort iteratively
Have you tried google ?
It is just common quicksort, when recursion is realized with array.
This is my effort. Tell me if there is any improvement possible.
This code is done from the book "Data Structures, Seymour Lipschutz(Page-173), Mc GrawHill, Schaum's Outline Series."
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define SIZE 12
struct StackItem
{
int StartIndex;
int EndIndex;
};
struct StackItem myStack[SIZE * SIZE];
int stackPointer = 0;
int myArray[SIZE] = {44,33,11,55,77,90,40,60,99,22,88,66};
void Push(struct StackItem item)
{
myStack[stackPointer] = item;
stackPointer++;
}
struct StackItem Pop()
{
stackPointer--;
return myStack[stackPointer];
}
int StackHasItem()
{
if(stackPointer>0)
{
return 1;
}
else
{
return 0;
}
}
void ShowStack()
{
int i =0;
printf("\n");
for(i=0; i<stackPointer ; i++)
{
printf("(%d, %d), ", myStack[i].StartIndex, myStack[i].EndIndex);
}
printf("\n");
}
void ShowArray()
{
int i=0;
printf("\n");
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", myArray[i]);
}
printf("\n");
}
void Swap(int * a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int Scan(int *startIndex, int *endIndex)
{
int partition = 0;
int i = 0;
if(*startIndex > *endIndex)
{
for(i=*startIndex ; i>=*endIndex ; i--)
{
//printf("%d->", myArray[i]);
if(myArray[i]<myArray[*endIndex])
{
//printf("\nSwapping %d, %d", myArray[i], myArray[*endIndex]);
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
else if(*startIndex < *endIndex)
{
for(i=*startIndex ; i<=*endIndex ; i++)
{
//printf("%d->", myArray[i]);
if(myArray[i]>myArray[*endIndex])
{
//printf("\nSwapping %d, %d", myArray[i], myArray[*endIndex]);
Swap(&myArray[i], &myArray[*endIndex]);
*startIndex = *endIndex;
*endIndex = i;
partition = i;
break;
}
if(i==*endIndex)
{
*startIndex = *endIndex;
*endIndex = i;
partition = i;
}
}
}
return partition;
}
int GetFinalPosition(struct StackItem item1)
{
struct StackItem item = {0};
int StartIndex = item1.StartIndex ;
int EndIndex = item1.EndIndex;
int PivotIndex = -99;
while(StartIndex != EndIndex)
{
PivotIndex = Scan(&EndIndex, &StartIndex);
printf("\n");
}
return PivotIndex;
}
void QuickSort()
{
int median = 0;
struct StackItem item;
struct StackItem item1={0};
struct StackItem item2={0};
item.StartIndex = 0;
item.EndIndex = SIZE-1;
Push(item);
while(StackHasItem())
{
item = Pop();
median = GetFinalPosition(item);
if(median>=0 && median<=(SIZE-1))
{
if(item.StartIndex<=(median-1))
{
item1.StartIndex = item.StartIndex;
item1.EndIndex = median-1;
Push(item1);
}
if(median+1<=(item.EndIndex))
{
item2.StartIndex = median+1;
item2.EndIndex = item.EndIndex;
Push(item2);
}
}
ShowStack();
}
}
main()
{
ShowArray();
QuickSort();
ShowArray();
}

Resources