C++程序获取用户输入时崩溃:科目代码数组问题排查
Hey there! Let's dig into why your program is crashing when handling the subject codes. From the code snippet you shared, here are the most likely culprits and how to fix them:
Your student_codes is a string* pointer, but there’s no sign you’re allocating memory for it before trying to store subject codes. If you directly assign values to student_codes[i] without first creating an array of strings, you’re accessing uninitialized "wild" memory—this is almost certainly why your program crashes.
Fix: After getting the number of subjects (numOfSubjects), allocate memory for the string array first:
void GetStudent(Student* student) { int numOfSubjects; cout << "Enter number of subjects: "; cin >> numOfSubjects; // Allocate memory for the subject codes array student->student_codes = new string[numOfSubjects]; // Now safely input each code for (int i = 0; i < numOfSubjects; ++i) { cout << "Enter subject code " << i+1 << ": "; cin >> student->student_codes[i]; } }
While this won’t cause an immediate crash, failing to deallocate memory allocated with new[] leads to memory leaks, which can cause unexpected behavior over time.
Fix: When you’re done using the Student object, free the array:
// When you no longer need the student data delete[] student.student_codes;
If you mix cin with getline later in your code, leftover newline characters in the input buffer can cause skipped prompts or empty inputs. This might not crash the program right away, but it can lead to invalid data that causes crashes downstream.
Fix: If you need to use getline after cin, clear the buffer first:
#include <limits> // Add this header for numeric_limits // After using cin >> something... cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Then use getline safely getline(cin, someStringVariable);
In C++, you don’t need typedef struct like you do in C. It’s cleaner to define your struct as:
struct Student { string student_number; string student_name; string* student_codes; };
This doesn’t fix crashes, but it makes your code more readable for other C++ developers.
Also, initialize the student_codes pointer to nullptr when creating a Student object—this prevents accidental access to wild memory if GetStudent isn’t called properly:
Student myStudent{"", "", nullptr};
If you can share the full GetStudent function or more details about exactly when the crash happens, I can help narrow it down even further!
内容的提问来源于stack exchange,提问作者Linus Haber

