I have a C++ simple queue console application, first display three main choices and ask user to choose: 1 enqueue, 2 dequeue, 3 exit. When user selects 1, it calls enqueue function and prompt user for input and then do the rest. The program is working fine when input is less than or equal to the max integer (2^31 − 1). When input is greater than the max int, the program goes to an infinite loop of displaying the three main choices. My question is that why the catch bad_alloc did not work when a greater-than-max int entered? Do you have any suggestions for how to handle this kind of memory exception? The following code is the enqueue function:
void Queue::enqueue()
{
int data;
node *temp = new node;
try
{
cout << "Enter the data to enqueue: ";
cin >> data;
temp->info = data;
temp->next = NULL;
if (front == NULL) front = temp;
else rear->next = temp;
rear = temp;
}
catch (bad_alloc)
{
cout << "Ran out of memory!" << endl;
}
}