Question

I'm trying to figure out why my program has an infinite loop. I'm pretty sure it...

I'm trying to figure out why my program has an infinite loop. I'm pretty sure it has something to do with the catch(bad_alloc) function or maybe the while (true) loop above it but I'm not sure. Can you help me figure out why i have an infinite loop and help me fix it? Thanks

----------------------------------

main.cc

----------------------------

#include
#include
#include
#include "numbers.h"

using namespace std;


int main()
{
Numbers N1, N2;
     
for(size_t i = 2; i < 16; i +=2)

   N1.add(i);

N1.display();

cout << std::endl;


N2 = N1;

for(int i = 0; i < 4; ++i)
  
   N2.remove_last();

for(size_t i = 5; i < 20; i += 5)
  
   N2.add(i);

N2.display();

unsigned long start, stop, running;

start = time(NULL);

size_t item = 0;

try{

   while(true){

   Numbers N3;

   for(int i = 0; i < 100; i++){

       N3.add(item);
       N3.display();
       ++item;

   }
   }

}

catch(bad_alloc){

   cout<<"Memory failure after adding " <

}

stop = time(NULL);

running = (stop - start)/60;

cout<


return 0;
}

--------------------------------------

numbers.h

------------------------------------

#include
class Numbers{
public:
void add(unsigned long item);
void resize();
void display();
void remove_last();
Numbers();
Numbers& operator = (const Numbers &other);

private:
unsigned long * data;
std::size_t used;
std::size_t capacity;

};

Numbers::Numbers(){
used = 0;
capacity = 5;
data = new unsigned long[capacity];
}

void Numbers::add(unsigned long item){
if (used == capacity){
resize();
}
data[used] = item;
++used;
}

void Numbers::resize(){
unsigned long *tmpdata;
tmpdata = new unsigned long[capacity+5];//Allocate bigger array
for (size_t i=0; i tmpdata[i] = data[i];//Copy data
}
long unsigned *temp = data;
delete[] temp;//delete old data
data = tmpdata;//reassign original data
capacity += 5;//update capacity
}

void Numbers::display(){
std::cout << "Displaying array...." << std::endl;
for (size_t i=0; i std::cout << data[i] << std::endl;
}
}

void Numbers::remove_last(){
--used;
}

Numbers& Numbers::operator = (const Numbers &other){
if (this != &other){
long unsigned *temp = data;
delete[] temp;
data = new long unsigned [other.capacity];
capacity = other.capacity;
used = other.used;
for (int i = 0; i < capacity; i++){
data[i] = other.data[i];
}
}
return *this;
}

Homework Answers

Answer #1

Hello,

It is due to the while loop, You have to use break to exit oput of the loop .

I have added the code to break, It will break when i becomes 100 and declared i , so that it can be accessed outsode for. The added part of the code is highlighted in bold.


#include "numbers.h"

using namespace std;

int main()

{

Numbers N1, N2;

for(size_t i = 2; i < 16; i +=2)

   N1.add(i);

N1.display();

cout << std::endl;

N2 = N1;

for(int i = 0; i < 4; ++i)

   N2.remove_last();

for(size_t i = 5; i < 20; i += 5)

   N2.add(i);

N2.display();

unsigned long start, stop, running;

start = time(NULL);

size_t item = 0;

try{

   int i=0;

   while(true){

   Numbers N3;

   for( i = 0; i < 100; i++){

   N3.add(item);

   N3.display();

   ++item;

   }

   if(i==100)

break;

   }

}

catch(bad_alloc){

   cout<<"Memory failure after adding " <<endl;

}

stop = time(NULL);

running = (stop - start)/60;

cout<<running;

return 0;

}


Thanks, let me know if there is any concern.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
How to stop the program from exiting after display detail. When there is food detail, it...
How to stop the program from exiting after display detail. When there is food detail, it will display and exit the program. What can i do to make it not exit the program and back to main menu. #include <iostream> #include <iomanip> #include<string.h> using namespace std; struct food{ int order_id; string food_code,flavor,customer_id; string address,name; int weight,unit_price,qty,contact_number; struct food *next; };    class Foodsystem{ food *head,*temp,*temp2,*end; static int id;    public: Foodsystem(){ head=NULL;end=NULL;} void Place_Order(); void View_food_details(); void Modify_food_details(); void Delete_food_details();...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity  ...
I'm having a warning in my visual studio 2019, Can anyone please solve this warning. Severity   Code   Description   Project   File   Line   Suppression State Warning   C6385   Reading invalid data from 'DynamicStack': the readable size is '(unsigned int)*28+4' bytes, but '56' bytes may be read.   Here is the C++ code were I'm having the warning. // Sstack.cpp #include "SStack.h" // Constructor SStack::SStack(int cap) : Capacity(cap), used(0) {    DynamicStack = new string[Capacity]; } // Copy Constructor SStack::SStack(const SStack& s) : Capacity(s.Capacity), used(s.used)...
Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 +...
Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 + … 1/n. Let’s estimate natural using n = 20. sum_thread.cpp #include <chrono> #include <iostream> #include <mutex> #include <random> #include <utility> #include <vector> #include <thread> using namespace std; constexpr long long size= 1000000; mutex myMutex; void sumUp(unsigned long long& sum, const vector<int>& val, unsigned long long beg, unsigned long long end){ long long localSum = 0; for (auto it= beg; it < end; ++it){ localSum+=...
Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 +...
Modify the sum_thread.cpp program to compute sum = 1 + 1/2 + 1/3 + 1/4 + … 1/n. Let’s estimate natural using n = 20. sum_thread.cpp #include <chrono> #include <iostream> #include <mutex> #include <random> #include <utility> #include <vector> #include <thread> using namespace std; constexpr long long size= 1000000; mutex myMutex; void sumUp(unsigned long long& sum, const vector<int>& val, unsigned long long beg, unsigned long long end){ long long localSum = 0; for (auto it= beg; it < end; ++it){ localSum+=...
For some reason I followed the steps in my project and I am getting the incorrect...
For some reason I followed the steps in my project and I am getting the incorrect output and when I am submitting it, it gives me compilation error. Printing empty array -- next line should be blank Testing append: Shouldn't crash! Should print 100 through 110 below, with 110 on a new line: 100 101 102 103 104 105 106 107 108 109 110 Checking capacity of new array: OK Append test #2: Should print 100 through 120 below, on...
i want to complete this code to insert a new node in the middle of list...
i want to complete this code to insert a new node in the middle of list (take a node data from user, search the node and insert new node after this node). this is the code #include <iostream> #include <stdlib.h> using namespace std ; struct Node{                int data;                Node *link ;}; struct Node *head=NULL, *tail=NULL; /* pointers to Node*/ void InsertFront(); void InsertRear(); void DeleteFront(); void DeleteRear(); int main(){                int choice;                do{                               cout << "1:...
my code has several functions; delete and backward functions are not working, rewrite the code for...
my code has several functions; delete and backward functions are not working, rewrite the code for both functions and check them in the main: #include<iostream> #include<cassert> using namespace std; struct nodeType {    int info;    nodeType *link; }; class linkedList { public:    void initializeList();    bool isEmptyList();    void print();    int length();    void destroyList();    void insertFirst(int newItem);    void insertLast(int newItem);    int front();    linkedList();    void copyList(const linkedList otherList);    void insertNewValue(int value);...
I'm currently stuck on Level 3 for the following assignment. When passing my program through testing...
I'm currently stuck on Level 3 for the following assignment. When passing my program through testing associated with the assignment it is failing one part of testing.   Below is the test that fails: Failed test 4: differences in output arguments: -c input data: a b c -c expected stdout: b observed stdout: a b expected stderr: observed stderr: ./test: invalid option -- 'c' Unsure where I have gone wrong. MUST BE WRITTEN IN C++ Task Level 1: Basic operation Complete...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
I am trying to solve the following C++ problem over structures. I am having trouble with...
I am trying to solve the following C++ problem over structures. I am having trouble with the very last structure and I made a comment next to where I am confused. I included the assignment instructions and my current code. I would appreciate if anyone can help me explain what I need to do for the last structure. Thank you. Assignment Instructions Create a program that will prompt me for each of the following items: 1. Date of Birth 2....