I am trying to delete a record from an entered position, from a dynamically allocated array in c++, and when i try to run the program it throws an error stating
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
The insertion and displaying of the records are running perfectly fine, the only thing that throws an error is delete operation.
The Code
#include <iostream>
using namespace std;
struct employee{
string name;
int empId;
string dept;
int age;
};
employee *emp = new employee[5];
void insertData(){
for (int i = 0; i<5; i++){
cout<<"Enter the Employee name"<<endl;
cin>>emp -> name;
cout<<"Enter the Employee Id"<<endl;
cin>>emp -> empId;
cout<<"Enter the Employee Department"<<endl;
cin>>emp -> dept;
cout<<"Enter the Employee age"<<endl;
cin>>emp -> age;
}
}
void displayData(){
for (int i = 0; i < 5; ++i) {
cout<<"Employee"<<i+1<<" Data"<<endl;
cout<<"Name : "<<emp -> name<<endl;
cout<<" Employe ID : "<<emp -> empId<<endl;
cout<<"Department : "<<emp -> dept<<endl;
cout<<"Age : "<<emp -> age<<endl<<endl;
}
}
void deleteData(){
int pos;
cout<<"Enter the position you want to delete Data";
cin>>pos;
if (pos>5){
cout<<"Invalid Size please enter a size smaller than 5";
}
for (int i = pos; i < 5; ++i) {
emp[i] = emp[i+1];
}
}
int menu(){
int x;
do {
int n;
cout << "Please enter the number corresponding to an operation you want to perform\n";
cout << "1. Insert Data" << endl;
cout << "2. Display Data" << endl;
cout << "3. Delete Data" << endl;
cout << "4. Exit" << endl;
cin >> n;
switch (n) {
case 1: {
insertData();
break;
}
case 2: {
displayData();
break;
}
case 3: {
deleteData();
break;
}
case 4: {
exit(0);
}
default:
cout << "Invalid Choice, Enter a valid choice";
return 1;
}
cout<<"Press 1 to continue or 0 to exit";
cin>>x;
} while (x == 1);
}
int main() {
menu();
return 0;
}