C++ Array values being altered at element 4 after throwing exception - c++

The requirements for the program state that the try/catch must be placed in the main.cpp as below:
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
When it accesses the method:
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
It doesn't seem to matter which variation of throwing I use, my array gets destroyed afterward. It works fine if it stays within bounds, or I work it to not throw from the method (doing the error checking elsewhere), but the requirements state that it has to be that way, so I must be missing something. Full code below:
main.h:
#ifndef MAIN_H
#define MAIN_H
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER
***********************************/
#include <iostream> /* cout, endl */
#include "mylist.h"
#include <stdexcept>
#define LISTSIZE 10
using std::cout;
using std::endl;
int elementResult;
#endif /* MAIN_H */
main.cpp:
#include "main.h"
int main(int argc, char** argv) {
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER AND
* UNCOMMENT THINGS AS YOU COMPLETE
* THE FUNCTIONALITY OF YOUR LIST OBJECT
***********************************/
/* This will create a "list" of size LISTSIZE
* and initialize it to all zeros */
cout << "create and initialize mylist" << endl;
MyList mylist(LISTSIZE);
mylist.printArray();
cout << endl;
/* This will set the list to all 50 */
cout << "set mylist to all 50" << endl;
mylist.setArray(50);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers -2 to 4" << endl;
mylist.setRandom(-2,4);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers 4 to 4" << endl;
mylist.setRandom(4,4);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 1-100 values */
cout << "attempt to set to random numbers 1 to 100" << endl;
mylist.setRandom(1,100);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 500-1000 values */
cout << "attempt to set to random numbers 500 to 1000" << endl;
mylist.setRandom(1000,500);
mylist.printArray();
cout << endl;
/* These next two sets will succeed and set the 1st and last
* elements to 1000 and 2000 respectively */
if(mylist.setElement(1000, 0)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(2000, LISTSIZE-1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
/* These next two sets will fail and leave the array unmodified */
if(mylist.setElement(9999, -1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(9999, LISTSIZE)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
cout << "Testing new and/or modified code..." << endl << endl;
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
mylist.printArray();
cout << "attempting to get element 4000 using: int getElement(int);" << endl;
try{
cout << mylist.getElement(4000) << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
cout << endl;
cout << "printing the array element by element using: int getElement(int,int*);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
if(mylist.getElement(i, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
cout << "attempting to get element 4000 using: int getElement(int,int*);" << endl;
if(mylist.getElement(4000, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
return 0;
}
mylist.h:
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream> /* cout, endl */
#include <stdlib.h> /* srand, rand, atoi */
#include <time.h> /* time */
#include <stdexcept>
// you can add libraries if you need them, but you shouldn't
// DO NOT MODIFY THESE DEFINES
#define RMIN 1
#define RMAX 10
#define DEFAULT_SIZE 10
using std::cout;
using std::endl;
class MyList {
public:
// DO NOT MODIFY THESES NEXT TWO
MyList(int); // constructor
~MyList(); // destructor
int getElement(int);
void setArray(int);
bool setElement(int, int);
void setRandom(int, int);
void printArray();
bool getElement(int, int*);
private:
// these are the only attributes allowed
// DO NOT ADD OR MODIFY THEM
int length;
int *array;
};
#endif //MYLIST_H
mylist.cpp:
#include "mylist.h"
// constructor
MyList::MyList(int size) {
srand(time(NULL)); // call only once!
if(size < 1){
size = DEFAULT_SIZE;
}
MyList::length = size;
MyList::array = new int(size);
setArray(0);
}
// destructor
MyList::~MyList() {
//delete[] MyList::array;
}
void MyList::printArray() {
cout << "[";
for (int i = 0; i < length; i++){
if (i == length - 1){
cout << array[i];
}else{
cout << array[i] << " ";
}
}
cout << "]" << endl;
}
void MyList::setArray(int setArrayTo){
for (int i = 0; i < length; i++){
MyList::array[i] = setArrayTo;
}
}
void MyList::setRandom(int numOne, int numTwo){
bool isValidRandom = true;
int randMin, randMax;
if((numOne < RMIN) || (numTwo < RMIN) || (numOne == numTwo)){ isValidRandom = false; }
if(isValidRandom == true){
if(numTwo < numOne){
randMin = numTwo;
randMax = numOne;
} else {
randMin = numOne;
randMax = numTwo;
}
} else {
randMin = RMIN;
randMax = RMAX;
}
for(int i = 0;i < length; i++){
MyList::array[i] = rand() % randMax + randMin;
}
}
bool MyList::setElement(int passedValue, int arrayIndex){
bool isInRange = true;
if ((arrayIndex < 0)||(arrayIndex > length - 1)){
isInRange = false;
}
if (isInRange == true){
MyList::array[arrayIndex] = passedValue;
}
return isInRange;
}
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
bool MyList::getElement(int passedIndex, int *iPtr){
bool isItValid = true;
if((passedIndex >= 0) && (passedIndex < length)){
*iPtr = MyList::array[passedIndex];
} else {
isItValid = false;
}
return isItValid;
}
Output

Related

Poker problem - Couldn't convert from 'int' to 'string'

I DONT WANT TO CONVERT ANYTHING :)
I'm making a small copy of poker for myself.
#include <iostream>
#include <ctime>
#include <string>
#include <cstdlib>
#include <windows.h>
using namespace std;
void welcome();
void rules();
void game();
void rateDeck(string deck[], int decksize);
bool findCard(string deck[], string card);
int main(){
srand(time(NULL));
welcome();
rules();
getchar();
game();
return 0;
}
void welcome(){
cout << "\t WELCOME \t" << endl;
cout << " TO THE POKER SIMULATOR" << endl;
cout << "\t KIND OF \t" << endl << endl;
}
void rules(){
cout << " \t RULES" << endl;
cout << "1. You get 5 cards at the beginning." << endl << "2. You can always pick more cards." << endl << "3. It's not a game. You just look at your cards and pick more." << endl << endl << "Have fun :)" << endl;
cout << endl << "PRESS ANYTHING TO START A GAME" << endl;
}
void game(){
// 24 cards
// Tr - trefl, Ka - Karo, Ki - Kier, Pi - Pik
// A - As, K - Krol, D - Dama, W - Walet, 10, 9
string cards[] = {
"TrA", "TrK", "TrD", "TrW", "Tr10", "Tr9",
"KaA", "KaK", "KaD", "KaW", "Ka10", "Ka9",
"KiA", "KiK", "KiD", "KiW", "Ki10", "Ki9",
"PiA", "PiK", "PiD", "PiW", "Pi10", "Pi9" };
string randomCard, lastCard;
bool repeat;
int decksize = 5;
string mydeck[] = {"KaA", "PiD", "KiW", "Ka10", "Pi9"};
system("cls");
cout << "My deck: " << endl;
for (int i=0; i<decksize; i++){
randomCard = cards[rand() % 24];
mydeck[i] = randomCard;
for (int j=0; j<=i-1; j++){
do{
mydeck[i] = randomCard;
if (mydeck[i]!=mydeck[j]) repeat=false;
} while(mydeck[j]==mydeck[i] && i!=0 && repeat==true);
}
if (i==0) cout << "karta nr: " << i << " " << mydeck[i] << endl;
else cout << "karta nr: " << i << " " << mydeck[i] << " Last Card:" << lastCard << endl;
lastCard = mydeck[i];
}
rateDeck(mydeck, decksize);
}
void rateDeck(string deck[], int decksize){
int royalFlush = 0;
int straightFlush = 0;
int fourOfKind = 0;
int fullHouse = 0;
int flush = 0;
int streigh = 0;
int threeOfKind = 0;
int twoPairs = 0;
int onePair = 0;
for (int i=0; i<decksize; i++){
string card[i] = { deck[i] };
if (i==decksize-1){
if( findCard(deck, decksize, "TrA") == true ) royalFlush+=1;
//&& findCard(deck, decksize, "TrK") && findCard(deck, decksize, "TrQ") && findCard(deck, decksize, "TrJ") && findCard(deck, decksize, "Tr10") ) royalFlush+=1;
}
}
}
bool findCard(string deck[], int decksize, string card){
for(int i=0; i<decksize; i++){
if(deck[i]==card) return true;
else return false;
}
}
void rateDeck(string deck[], int decksize){
for (int i=0; i<decksize; i++){
string card[i] = { deck[i] };
if (i==decksize-1){
if( findCard(deck, decksize, "TrA") == true ) royalFlush+=1;
}
}
}
Function findCard() goes through the deck and looks for a card. If it exists it return true, otherwise false. The problem is in the last line - if statement.
Result:
error: could not convert 'decksize' from 'int' to 'std::__cxx11::string' {aka'std::__cxx11::basic_string<char>'}|
Btw. function is called in another function where "deck" is "string deck[]" and "decksize" is "int decksize".
Edit1: rateDeck func is used to describe the deck. If there is a Flush or Full House (Poker names) it should show it.

Debug Assertion Fails On Dynamic Array

So here is my working code for a simple dynamic array. This has to be a sample code for a very entry level data structure implementation:
#include <iostream>
using namespace std;
class AdvancedArray {
public:
AdvancedArray();
~AdvancedArray();
int get_size() const; // get the number of elements stored
double& at(int idx) const; // access the element at idx
void push_back(double d); // adds a new element
void remove(int idx); // remove the element at idx
void clear(); // delete all the data stored
void print() const;
private:
double* elements;
int size;
};
int main()
{
AdvancedArray* arr = new AdvancedArray();
cout << "The Array Size is: " << arr->get_size() << endl;
cout << "Pusing Values: 1.2, 2.1, 3.3, 4.5 in the Array. " << endl;
arr->push_back(1.2);
arr->push_back(2.1);
arr->push_back(3.3);
arr->push_back(4.5);
arr->print();
cout << "The Array Size is: " << arr->get_size() << endl;
cout << "The Element at Index 2 is: " << arr->at(2) << endl;
cout << "Deleting Values: 2.1 from the Array. " << endl;
arr->remove(1);
cout << "The Array Size is: " << arr->get_size() << endl;
arr->print();
cout << "Clearing the Array: " << endl;
arr->clear();
cout << "The Array Size is: " << arr->get_size() << endl;
arr->clear();
return 0;
}
AdvancedArray::AdvancedArray()
{
size = -1;
elements = new double[100]; //Maximum Size of the Array
}
AdvancedArray::~AdvancedArray()
{
delete[] elements;
}
int AdvancedArray::get_size() const
{
if(size < 0)
{
return 0;
}
return size;
}
double & AdvancedArray::at(int idx) const
{
if (idx < 100 && idx >= 0 && size > 0) {
return elements[idx];
}
cout << "Index Out of Bounds." << endl;
}
void AdvancedArray::push_back(double d)
{
if (size >= 100)
{
cout << "Overflow Condition. No More Space!" << endl;
}
else
{
elements[++size] = d;
cout << "Element Pushed In Stack Successfully!" << endl;
}
}
void AdvancedArray::remove(int idx)
{
if (size >= 100 || size < 0)
{
cout << "No Such Element Exists!" << endl;
}
else
{
for(int i = idx; i <size; i++)
{
elements[idx] = elements[idx + 1];
}
size--;
cout << "Element Deleted In Stack Successfully!" << endl;
}
}
void AdvancedArray::clear()
{
delete[] elements;
size = -1;
}
void AdvancedArray::print() const
{
cout << "[ ";
for(int i = 0; i <= size; i++)
{
cout << elements[i] << " ";
}
cout << "]" << endl;
}
So every time I try to run this I have the 2 problems:
What is wrong with my code? Why is the heap getting corrupted (I searched about the error code and that's all has to say)? Is my code doing some major access violations? I am using VS2015.
You do delete [] elements three times without setting elements to nullptr in between. That leads to undefined behavior the second time (and third) time.
When size == 99, the following piece of code attempts to access elements[100]:
if (size >= 100)
{
cout << "Overflow Condition. No More Space!" << endl;
}
else
{
elements[++size] = d;
cout << "Element Pushed In Stack Successfully!" << endl;
}
You need to change ++size to size++.

Memory being messed up while searching for relation in family tree

I am implementing class of wizards in this code but I have a serious problem with finding relation in wizards family tree. I am using a back tracking method to find all relation between two nodes but memory will start to being messed up in the middle of the task and I have no idea what should I do.
Here you can see implementation of this class using C++.
#include "Wizard.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Wizard::Wizard(string first_name, string surname, string occupation, string organization, string wand)
: first_name(first_name),surname(surname), occupation(occupation), organization(organization), wand(wand)
{
this->married=0;
this->wand="Dragon Hearstring";
this->occupation="Auror";
this->organization="Dumbledore Army";
};
void Wizard::set_first_name(string _name){
this->first_name = _name;
}
void Wizard::set_surname(string _surname){
this->surname = _surname;
}
void Wizard::set_occupation(string _occupation){
this->occupation = _occupation;
}
void Wizard::set_organization(string _organization){
this->organization = _organization;
}
void Wizard::set_wand(string _wand){
this->wand = _wand;
}
string Wizard::get_name(){
string name;
name = first_name + " " + surname;
return name;
}
string Wizard::get_occupation(){
return occupation;
}
string Wizard::get_organization(){
return organization;
}
string Wizard::get_wand(){
return wand;
}
void Wizard::print_parents(){
cerr << "Parents: ";
for (int i=0; i<parents.size(); i++){
cout << parents[i]->get_name();
if ( i!= parents.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_siblings(){
cerr <<"Siblings: ";
for (int i=0; i<siblings.size(); i++){
cout << siblings[i]->get_name();
if ( i < siblings.size() -1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::print_spouse(){
cerr <<"Spouse: ";
if (married==1)
cout << spouse->get_name();
cout << endl;
}
void Wizard::print_children(){
cerr <<"Children: ";
for (int i=0; i<children.size(); i++){
cout << children[i]->get_name();
if ( i < children.size() - 1){
cout << " & ";
}
}
cout << endl;
}
void Wizard::operator*(Wizard& _spouse){
this->married=1;
_spouse.married=1;
cout << this->get_name() << " and " << _spouse.get_name() << endl;
this->spouse = &_spouse;
_spouse.spouse = this;
_spouse.print_spouse();
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(&_spouse);
for (int i=0; i<this->children.size(); i++)
children[i]->parents = these_two;
for (int i=0; i<_spouse.children.size(); i++)
children[i]->parents = these_two;
}
void Wizard::operator+(Wizard& _child){
if (!search_in_vector(this->children,&_child))
this->children.push_back(&_child);
if (!search_in_vector(this->spouse->children,&_child))
this->spouse->children.push_back(&_child);
vector< Wizard* > these_two;
these_two.push_back(this);
these_two.push_back(this->spouse);
_child.parents=these_two;
_child.surname = this->surname;
for (int i=0; i<this->children.size(); i++){
if(!search_in_vector(_child.siblings,children[i]) && (children[i]!=&_child)){
_child.siblings.push_back(children[i]);
children[i]->siblings.push_back(&_child);
}
}
}
void Wizard::print_relation_with(Wizard& john_doe){
vector<string> path2;
vector< vector< string > > path1;
vector<Wizard*> nodes_in_the_way;
nodes_in_the_way.push_back(this);
if (this->get_name() == john_doe.get_name()){
cout << this->get_name() << " is " << john_doe.get_name() << endl;
return;
}
this- >search_for_relation(*this,john_doe,path1,path2,nodes_in_the_way);
if (path1.size() == 0){
cout << "no relation" << endl;
return;
}
path2=path1[0];
for (int i=1;i<path1.size();i++){
if (path1[i].size() < path2.size())
path2=path1[i];
}
cout << this->get_name() << " is ";
for (int i=0; i<path2.size(); i++)
cout << path2[i] << " of ";
cout << john_doe.get_name() << endl;
}
void Wizard::search_for_relation(Wizard& a,Wizard& b,vector< vector<string> > &path1,vector<string> &path2,vector< Wizard* > &nodes_in_the_way){
cerr << "////////////" << endl;
cerr << "IM INSIDE " << a.get_name() << " , SEARCHING FOR " << b.get_name() << " - " << path2.size() << endl;
cout << "PATH: ";
for (int i=0;i<nodes_in_the_way.size();i++)
cout << nodes_in_the_way[i]->get_name() << " ";
cout << endl;
a.print_spouse();
a.print_children();
a.print_parents();
if (a.get_name() == b.get_name() && path2.size()==0){
return;
}
if (a.get_name() == b.get_name() ){
path1.push_back(path2);
return;
}
if (a.married){
if (!search_in_vector(nodes_in_the_way,a.spouse)){
path2.push_back("spouse");
nodes_in_the_way.push_back(a.spouse);
search_for_relation(* (a.spouse),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// parents
for (int i=0;i<a.parents.size();i++){
if (!search_in_vector(nodes_in_the_way,a.parents[i])){
path2.push_back("child");
nodes_in_the_way.push_back(a.parents[i]);
search_for_relation(* (a.parents[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
// children
for (int i=0;i<a.children.size();i++){
if (!search_in_vector(nodes_in_the_way,a.children[i])){
path2.push_back("parent");
nodes_in_the_way.push_back(a.children[i]);
search_for_relation(* (a.children[i]),b,path1,path2,nodes_in_the_way);
path2.pop_back();
nodes_in_the_way.pop_back();
}
}
}
///////////// NON-METHOD FUNCITONS ///////////////
bool search_in_vector(vector< Wizard* > a,Wizard* b){
for (int i=0; i<a.size(); i++)
if (a[i]->get_name() == b->get_name())
return true;
return false;
}
So that was the code.
Here you can see the output after some back_tracking:
Here you see that Harry's information has been messed up during last recursion and the executable file can't print his parents.
Please let me know that I'm doing wrong! Thanks!

C++ class and function output issue

I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation

_BLOCK_TYPE_IS_VALID_ and CrtIsValidHeapPointer assertion errors after int main() return stmt

I get the following assertion errors after the control passes the return statement:
_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
CrtIsValidHeapPointer(pUserData)
while trying to run this code:
main.cpp
#include <iostream>
#include "Queue.h"
#include "Customer.h"
using namespace std;
int main() {
Queue q1;
Queue q2(3);
Queue q3(5);
for (int i = 0; i < 13; i++)
{
Customer c(i);
bool in = q1.enqueue(c);
if (i <= 9 && !in)
{
cout << "ERROR: default size is smaller than 10!!" << endl;
}
else if (i > 9 && in)
{
cout << "ERROR: default size is bigger than 10!!" << endl;
}
}
q1.print();
cout << "0 1 2 3 4 5 6 7 8 9 ***********" << endl;
for (int i = 0; i < 10; i++)
{
Customer el = q1.dequeue();
if (i != el.getId()){
cout << "Error: dequeue order is not correct!!";
}
}
cout << endl;
Customer underflow = q1.dequeue();
if (underflow.getId() != 0)
{
cout << "ERROR: underflow not taken care of!!" << endl;
}
Customer c1(12, "moni");
if (!q3.enqueue(c1))
{
cout << "ERROR: cannot add element to queue 3!!" << endl;
}
Customer c2(14, "mobi");
if (!q3.enqueue(c2)){
cout << "ERROR: cannot add element to queue 3!!" << endl;
}
Queue q4(q3);
if (q3.dequeue().getId() != 12)
{
cout << "ERROR: cdequeue should return the first element in line (12)!!" << endl;
}
if (!q4.enqueue(21)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (!q4.enqueue(7)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (!q4.enqueue(332)){
cout << "ERROR: cannot add element to queue 4!!" << endl;
}
if (q4.enqueue(12)){
cout << "ERROR: add element number 6 to queue with size 5 (q4)!!" << endl;
}
q4.print();
cout << "12 14 21 7 332 ***********" << endl;
q3.print();
cout << "14 ***********" << endl;
q2.print();
cout << "queue is empty! ***********" << endl;
q2 = q3;
q2.print();
cout << "14 ***********" << endl;
if (!q2.enqueue(17)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
if (!q2.enqueue(18)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
if (!q2.enqueue(3521)){
cout << "ERROR: cannot add element to queue 2!!" << endl;
}
q2.print();
cout << "14 17 18 3521 ***********" << endl;
q3.print();
cout << "14 ***********" << endl;
return 0;
}
Queue.h
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stdio.h>
#include "Customer.h"
class Queue {
private:
Customer *elements; // Holds the elements of this queue.
int mSize; // Size of the queue
int mTop; // Index of the last element in the queue.
public:
static const int DEFAULT_SIZE = 10;
// Default constructor
Queue() : mSize(DEFAULT_SIZE), mTop(-1) {
elements = new Customer[DEFAULT_SIZE];
}
// Copy constructor
Queue(const Queue &q) : mSize(q.mSize), mTop(q.mTop) {
elements = new Customer[mSize];
for(int i = 0; i <= mTop; i++){
elements[i] = q.elements[i];
}
}
// Initialize a new Queue with the specified size.
explicit Queue(int size) : mSize(size), mTop(-1) {
elements = new Customer[size];
}
// Add the given Customer to the end of the queue.
// Returns true if the Customer was added, false if the Queue is full.
bool enqueue(Customer);
// Remove the first Customer from the Queue.
// Returns the Customer that was removed.
Customer dequeue();
// Print the IDs of the Customers in this Queue in the order
// in which they will be attended.
void print() const;
~Queue() {
delete[] elements;
}
};
#endif
Any ideas?
Took a quick look so but I think the problem is somewhere in your implementation of bool enqueue(Customer).
When you do the following:
Customer c(i);
bool in = q1.enqueue(c);
what is happening in enqueue? Is a copy of Customer being made properly?
Not specifically an answer but I think this will drive you in the right direction or perhaps you can post the code for Customer?