C++动态分配数组删除数据时触发std::bad_alloc错误求助
解决C++动态数组删除操作触发
std::bad_alloc的问题 错误原因分析
- 数组越界访问:
deleteData函数中,循环for (int i = pos; i < 5; ++i)会在i=4时访问emp[5],超出了动态数组new employee[5]的合法下标范围(0-4)。越界访问会破坏内存结构,最终触发std::bad_alloc异常。 - 位置处理逻辑错误:用户输入的位置通常从1开始计数,但数组下标从0开始,直接使用
pos作为下标会导致逻辑偏移;同时未校验pos<=0的非法输入。 - 插入/显示函数的元素访问错误:
insertData和displayData中始终使用emp->操作元素,这只会修改/读取数组的第一个元素,导致所有数据被覆盖到第一个位置,后续元素未被正确处理。
修正后的代码
#include <iostream> using namespace std; struct employee{ string name; int empId; string dept; int age; }; employee *emp = new employee[5]; int empCount = 0; // 跟踪当前有效员工数量 void insertData(){ if (empCount >= 5) { cout << "数组已满,无法插入更多员工" << endl; return; } for (int i = 0; i < 5; i++){ cout << "Enter the Employee name" << endl; cin >> emp[i].name; cout << "Enter the Employee Id" << endl; cin >> emp[i].empId; cout << "Enter the Employee Department" << endl; cin >> emp[i].dept; cout << "Enter the Employee age" << endl; cin >> emp[i].age; empCount++; } } void displayData(){ for (int i = 0; i < empCount; ++i) { cout << "Employee" << i+1 << " Data" << endl; cout << "Name : " << emp[i].name << endl; cout << "Employee ID : " << emp[i].empId << endl; cout << "Department : " << emp[i].dept << endl; cout << "Age : " << emp[i].age << endl << endl; } } void deleteData(){ if (empCount == 0) { cout << "没有员工数据可删除" << endl; return; } int pos; cout << "Enter the position you want to delete Data (1-" << empCount << "): "; cin >> pos; if (pos < 1 || pos > empCount){ cout << "Invalid position, please enter a number between 1 and " << empCount << endl; return; } int index = pos - 1; for (int i = index; i < empCount - 1; ++i) { emp[i] = emp[i+1]; } empCount--; } 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" << endl; break; } cout << "Press 1 to continue or 0 to exit: "; cin >> x; } while (x == 1); return 0; } int main() { menu(); delete[] emp; // 释放动态分配的内存 return 0; }
关键修正说明
- 修复越界问题:删除操作的循环条件改为
i < empCount - 1,避免访问超出有效元素范围的内存;同时将用户输入的位置转换为数组下标(pos-1)。 - 新增有效计数:用
empCount跟踪有效员工数量,插入时检查数组是否已满,删除时递减计数,显示时只遍历有效元素。 - 修正元素访问:将
emp->改为emp[i],确保每个数组元素被正确赋值和读取。 - 完善输入校验:删除操作中校验位置合法性,避免非法输入导致错误。
- 内存释放:程序结束前释放动态数组,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Ankit Verma
相关产品推荐
相关产品推荐

