从文件读取数据填充结构体数组并返回指针时出现段错误求分析
C++代码段错误(Segmentation Fault)问题排查需求
以下C++代码运行时触发「signal: segmentation fault (core dumped)」错误,需求是通过readCarList()函数返回Car类型数组指针来初始化结构体数组。
/* This code results in "signal: segmentation fault (core dumped)" The code requires that an array of structures be initialized with the returned pointer to an array of type Car from the readCarList() function **/ #include <iostream> #include <fstream> #include <iomanip> using namespace std; enum vehicleColor { blue, red, orange, silver, black, green }; struct Car { string brand, model; int mileage, year; vehicleColor color; // enum type variable }; // function declaration Car *readCarList(string file, int numCars); int main() { int numCars = 10; string fileName = "cars.txt"; //cout << "Enter a filename:" cout <<" //calling the function.... " << endl; //Use readCarList function to initalize dynamic array of structures Car * vehicle = readCarList(fileName, numCars); printCarList(vehicle, numCars); // Call print car list(structArray, 10) delete vehicle; // Delete memory to avoid leak } Car *readCarList(string fileName, int numCars) { cout << "Inside of readCarList function"; int count = 0; string car_color_temp[6]; //open file for reading ifstream inputFile; inputFile.open(fileName); Car * totalCars; // Pointer to Car variable totalCars = new Car[numCars];//Allocate space for 10 elements // Read in data from file into each for (int a = 0; a < numCars; a++) { inputFile >> totalCars[a].brand; inputFile >> totalCars[a].model; inputFile >> totalCars[a].mileage; inputFile >> car_color_temp[a]; //String array for holding color inputFile >> totalCars[a].year; //Convert value read into string array, into structarray[a].color (ENUM data type) if (car_color_temp[a] == "blue") totalCars[a].color = blue; else if (car_color_temp[a] == "red") totalCars[a].color = red; else if (car_color_temp[a] == "orange") totalCars[a].color = orange; else if (car_color_temp[a] == "silver") totalCars[a].color = silver; else if (car_color_temp[a] == "black") totalCars[a].color = black; else if (car_color_temp[a] == "green") totalCars[a].color = green; } return totalCars; }
输入文件cars.txt的格式为每行一项信息,每5行对应一辆车的品牌、型号、里程、颜色(枚举类型)、年份,示例如下:
Ford F-150 200456 blue 2014
已掌握相关课程内容,程序有预期输出,但不需要直接解决问题,仅希望明确代码中的错误点。
内容的提问来源于stack exchange,提问作者damian moore
相关产品推荐
相关产品推荐

