所以我毕业于学习C并且现在正在学习C ++。据我所知,C和C ++在各种方面都相似,所以我试图将过去的C项目文件重新编写成C ++。但是,当我尝试打印出我的信息时,我不断收到内存泄漏。有人能告诉我为什么我的代码中会出现内存泄漏。
typedef struct student_info {
char last[10];
char first[10];
int student_id;
int count_student;
} student;
typedef struct course_info {
char name[10];
int course_id;
int count_course;
student *students;
} course;
typedef struct gradebook_info {
course *courses;
} gradebook;
void new_course(gradebook *info) {
int i, loop=0;
cout << "Enter Number of Courses " ;
cin >> loop;
for(i=0; i<loop; i++) {
cout << "Enter Course ID ";
cin >> info->courses[info->courses->count_course].course_id;
cout << "Enter Course Name ";
cin >> info->courses[info->courses->count_course].name;
info->courses->count_course++;
}
}
void new_student(gradebook *info) {
int i, loop=0;
cout << "Enter Number of Students " ;
cin >> loop;
for(i=0; i<loop; i++) {
cout << "Enter Student ID ";
cin >> info->courses->students[info->courses->students->count_student].student_id;
cout << "Enter Last Name ";
cin >> info->courses->students[info->courses->students->count_student].last;
cout << "Enter First Name ";
cin >> info->courses->students[info->courses->students->count_student].first;
info->courses->students->count_student++;
}
}
void printCourse(gradebook *info) {
int i;
cout << "Course ID\tCourse Name\t" << endl;
for(i=0; i<info->courses->count_course; i++) {
cout << info->courses[i].course_id << "\t\t";
cout << info->courses[i].name << endl;
}
}
void printStudent(gradebook *info) {
int i;
cout << "Student ID\tLast Name\tFirst Name\t" << endl;
for(i=0; i<info->courses->students->count_student; i++) {
cout << info->courses->students[i].student_id << "\t\t";
cout << info->courses->students[i].last << "\t\t";
cout << info->courses->students[i].first << endl;
}
}
new_course()
功能时,它可以正常工作。printCourse()
功能。new_student()
功能。printStudent()
功能时,它可以正常工作。printCourse()
函数,当i=2
时,我从结构学生那里得到一些信息。我无法弄明白。任何帮助表示赞赏。
gradebook *info = new gradebook; //allocate memory
do {
main_menu();
int option=0;
switch(option) {
case 1: new_course(info);
break;
case 2: new_student(info);
break;
case 3: printCourse(info);
break;
case 4: printStudent(info);
break;
}
}while(option < 13);
delete(info);
答案 0 :(得分:0)
您不仅要为gradebook
分配内存,还要为courses
和students
分配内存。例如:
gradebook *info = new gradebook;
info->courses = new course_info[10];
for(int i = 0; i < 10; i++)
info->courses[i]->students = new student_info[10];
请注意,此示例将每门课程和学生数量限制为10个。
P.S。:如果您没有为courses
和students
分配内存,那么您的代码可能会进行一到两次迭代。但在这种情况下,你搞砸了你的记忆。
答案 1 :(得分:0)
您需要使用students
分配指针course
和new
。
获得循环后:
students = new student_info* [loop]
和
courses= new course_info* [loop]