C++ 获取集合方法的致命错误

C++ 获取集合方法的致命错误,c++,memory-management,memory-leaks,malloc,C++,Memory Management,Memory Leaks,Malloc,所以我正在为学校写一个模拟成绩册的大程序。我已经讨论了好几天了,为什么每当我创建新课程时,它都会随机给我运行时错误。奇怪的是,这只是有时候。有时,它的工作与飞行的颜色,有时不是。错误代码是线程1:EXC\U BAD\U访问(代码=1,地址=0x3002) 当我将用户输入分配给课程类数组中的一个成员时,就会出现这个错误。代码可能会给我带来更多好处 下面是类的定义,我将对经常出现此错误的行进行注释。给出错误的主要错误在课程中 // // Classes.hpp // Hw2 // // Cre

所以我正在为学校写一个模拟成绩册的大程序。我已经讨论了好几天了,为什么每当我创建新课程时,它都会随机给我运行时错误。奇怪的是,这只是有时候。有时,它的工作与飞行的颜色,有时不是。错误代码是线程1:EXC\U BAD\U访问(代码=1,地址=0x3002) 当我将用户输入分配给课程类数组中的一个成员时,就会出现这个错误。代码可能会给我带来更多好处

下面是类的定义,我将对经常出现此错误的行进行注释。给出错误的主要错误在课程中

//
//  Classes.hpp
//  Hw2
//
//  Created by Devin Tripp on 2/28/18.
//  Copyright © 2018 Devin Tripp. All rights reserved.
//


#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;


#define CHUNKSIZE 2

class Student {
private:
    int stud_id;
    string name;
public:
    void setId(int id) { stud_id = id;}
    int getId() { return stud_id;}
    void setName(string n) { name = n; } // I recieve an error here sometimes
    string getName() { return name;}
};

class Students {
public:
    Students() {stud_cnt = 0; stud_cap = CHUNKSIZE; studs = new Student[CHUNKSIZE];}
    ~Students() { delete [] studs;}
    void addStudent();
    void printStudents();
    int getstud_cap();
    Student* getStuds();
    void storeStuds();
    void loadStuds();
private:
    int stud_cnt;
    int stud_cap;
    Student *studs;
};

class Course {
private:
    int course_id;
    string course_name;
public:
    void setID(int id) {course_id = id;}
    int getID() { return course_id;}
    void setCourseName(string name) { course_name = name;} // Recieve error here // still getting this error here with new changes
    string getCourseName() { return course_name;}
};

class Courses {
public:
    Courses() {course_cnt = 0; course_cap = CHUNKSIZE; course_list = new Course[CHUNKSIZE]; for (int i = 0; i < course_cap; i++){
    course_list[i].setID(-1);
    course_list[i].setCourseName("");                 //This still produces the same error
}}
    ~Courses() { delete [] course_list;}
    void addCourse();
    void printCourses();
    int getCourseCnt() {return course_cnt;}
    int getCourseCap() {return course_cap;}
    Course *getCourseList() {return course_list;}
    void loadCourses();
    void storeCourses();

private:
    int course_cnt;
    int course_cap;
    Course *course_list;

};


class Enrollment {
public:
    int getEnId() {return en_ID;}
    int getCourse_ID() {return course_ID;}
    string getCName() {return courseName;}
    string getSName() {return studentsNames;}
    int getStudID() {return studs_ID;}
    void setEnID(int id) { en_ID = id; }
    void setCourse_ID(int id) {course_ID = id;}
    void setCName(string name) { courseName = name; } // Recieve error here sometimes
    void setSname(string name) { studentsNames = name; }
    void setStudID(int id) {studs_ID = id;}
    void setGrades(int grade, int num) { grades[num] =  grade;}


private:
    int en_ID;
    int course_ID;
    string courseName;
    int studs_ID;
    string studentsNames;
    int change_this;
    int grades[9];



};

class Enrollments {
public:
    Enrollments() {enroll_cnt = 0; enroll_cap = CHUNKSIZE; enroll_list = new Enrollment[CHUNKSIZE];}
    ~Enrollments() { delete [] enroll_list;}
    void addEnrollment(Students s, Student *studs, Courses c, Course *cList);
    void printCourseStudent();
    void getAverage();
    void GetletterGrade();
    void addGradesToCourse();

    void loadEnrollments();
    void saveEnrollments();

private:
    int enroll_cnt;
    int enroll_cap;
    Enrollment *enroll_list;
};
//
//1.hpp
//Hw2
//
//由Devin Tripp于2018年2月28日创建。
//版权所有©2018 Devin Tripp。版权所有。
//
#包括
#包括
#包括
使用名称空间std;
#定义块大小2
班级学生{
私人:
智力测验;
字符串名;
公众:
void setId(int id){stud_id=id;}
int getId(){return stud_id;}
void setName(string n){name=n;}//我有时在这里收到一个错误
字符串getName(){return name;}
};
班级学生{
公众:
Students(){stud_cnt=0;stud_cap=CHUNKSIZE;studs=new Student[CHUNKSIZE];}
~Students(){delete[]studs;}
void addStudent();
无效打印学生();
int getstud_cap();
学生*getStuds();
空心螺柱();
空负荷螺柱();
私人:
国际研究中心;
内螺柱帽;
学生*钉;
};
班级课程{
私人:
国际课程号;
字符串课程名称;
公众:
void setID(int id){course_id=id;}
int getID(){return course_id;}
void setCourseName(字符串名称){course\u name=name;}//此处接收错误//仍在此处获取此错误,并进行了新的更改
字符串getCourseName(){return course_name;}
};
班级课程{
公众:
Courses(){course\u cnt=0;course\u cap=CHUNKSIZE;course\u list=new course[CHUNKSIZE];for(int i=0;i
这是这些类的所有函数。在我添加存储和加载函数时,存储和加载函数开始导致这些问题,因此可能是函数中的某些内容。我认为这与字符串有关,因为它只在设置字符串的函数上有这个错误

//
//  Classes.cpp
//  Hw2
//
//  Created by Devin Tripp on 2/28/18.
//  Copyright © 2018 Devin Tripp. All rights reserved.
//

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "Classes.hpp"
#include <fstream>

using namespace std;

int Students::getstud_cap() {
    return stud_cap;
}

void Students::addStudent() {
    int id;
    string temp;

    if (stud_cnt == stud_cap) {
        Student *temp;
        temp = new Student[stud_cap + CHUNKSIZE];
        for (int i = 0;i < stud_cnt; i++) {
            temp[i] = studs[i];
        }

        delete [] studs;
        stud_cap += CHUNKSIZE;
        studs = temp;

    }

    printf("Enter a new student ID: ");
    cin >> id; cin.ignore();
    printf("Enter Name: ");
    cin >> temp; cin.ignore();
    cout << "Got data " << temp << endl;

    studs[stud_cnt].setId(id); cout << "Set ID" << endl;
    studs[stud_cnt].setName(temp); cout << "Set Name" << endl;
    stud_cnt += 1; cout << "inc stud count" << endl;




}

void Students::printStudents() {

    for (int i = 0; i < stud_cap; i++)  {

        cout << studs[i].getName() << " " << studs[i].getId() << endl;
    }

}

void Courses::addCourse() {
    int id;
    string name;


    if (course_cnt == course_cap) {
        // increase the size of the array

        Course *temp;
        temp = new Course[course_cap + CHUNKSIZE];

        for(int i =0; i < course_cnt; i++){
            temp[i] = course_list[i];
        }
        delete [] course_list;
        course_cap += CHUNKSIZE;
        course_list = temp;
    }

    printf("Whats the Course ID?: ");
    cin >> id; cin.ignore();
    printf("Enter the Name of The Course: ");
    cin >> name; cin.ignore();
    cout << " Got data " << name << endl;

    if (name == "") {
        cin >> name;
    }



    course_list[course_cnt].setID(id);
    course_list[course_cnt].setCourseName(name);


    course_cnt += 1;
}

void Courses::printCourses() {

    for( int i = 0; i < course_cap; i++)
        cout << course_list[i].getID() << endl;
}

Student* Students::getStuds(){
    return studs;
}


void Enrollments::addEnrollment(Students s, Student *studs, Courses c, Course *cList) {
    s.printStudents();
    int id;
    int courseNum;
    int tempI = -1;
    int tempITwo = -1;

    /*Check if you need to alloc more memory to the array. */


    if (enroll_cnt == enroll_cap){
        // alloc more space chunksize has been reached
        // create temp to hold the previous array
        Enrollment *temp;
        temp = new Enrollment[enroll_cap + CHUNKSIZE];
        for (int i = 0; i < enroll_cap; i++){
            temp[i] = enroll_list[i];
        }

        delete [] enroll_list;

        enroll_list += CHUNKSIZE;
        enroll_list = temp;
    }


    /* Find the student and the course */
    cout << "Type the students id: " << endl;
    cin >> id; cin.ignore();


    // loop through to find if the user typed in a number that matches the student id
    for (int i = 0; i < s.getstud_cap(); i++) {
         if(id == studs[i].getId()) {
             //save the i
             tempI = i;
         }
    }

    // check if it found the id or if the user typed in a wrong one
    if (tempI != -1){
        c.printCourses();
        cout << "Type the course number: " << endl;
        cin >> courseNum; cin.ignore();

        // check where in the array the id for the course is

        for(int i = 0; i < c.getCourseCap(); i++){
            if(courseNum == cList[i].getID()){
                tempITwo = i;
            }
        }


        // save the enrollment
        if (tempITwo != -1){
            enroll_list[enroll_cnt].setCName(cList[tempITwo].getCourseName());
            enroll_list[enroll_cnt].setCourse_ID(cList[tempITwo].getID());
            enroll_list[enroll_cnt].setSname(studs[tempI].getName());
            enroll_list[enroll_cnt].setStudID(studs[tempI].getId());
            enroll_list[enroll_cnt].setEnID(studs[tempI].getId() + cList[tempITwo].getID());

        } else {
            //wrong courseID
            cout << "You typed in an invalid course ID" << endl;
        }
    } else {
        //wrong student id
        cout << "You typed an invalid Student ID" << endl;
    }


    enroll_cnt += 1;
}


void Enrollments::printCourseStudent(){

    for (int i = 0; i < enroll_cap; i++) {

        cout << "Enrollment ID: " << enroll_list[i].getEnId() << " Course: " << enroll_list[i].getCName() << " Course ID: " << enroll_list[i].getCourse_ID() << " Student Name: " << enroll_list[i].getSName() << " Student ID: " << enroll_list[i].getStudID() << endl;
    }



}

void Enrollments::addGradesToCourse() {
    printCourseStudent();
    int id, count = 0, grade, tempI = -1;
    cout << "Type the enrollment ID: " << endl;
    cin >> id; cin.ignore();
    for(int i = 0; i < enroll_cap; i++){
        if (id == enroll_list[i].getEnId()) {
            tempI = i;

        }
    }

    if (tempI != -1){
        for (int i = 0; i < 10; i++){
            cout << "Enter grade " << count + 1 << ": ";
            cin >> grade; cin.ignore();

            enroll_list[tempI].setGrades(grade, count);
            count++;
        }

    }


}


void Courses::loadCourses(){

    ifstream fin;
    int id;
    string name;
    fin.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/courses.dat");
    fin >> course_cnt; fin.ignore();
    course_list = new Course[course_cnt];

    for ( int i=0; i < course_cnt; i++) {

        fin >> id >> name;
        course_list[i] .setCourseName(name);
        course_list[i].setID(id);
    }
    fin.close();

}

void Courses::storeCourses() {
    ofstream fout;
    fout.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/courses.dat");
    fout << course_cnt << endl;
    for ( int i=0; i < course_cnt; i++) {

        fout << course_list[i].getID() << " " <<  course_list[i].getCourseName() << endl;
    }
    fout.close();
}

void Students::loadStuds(){

    ifstream fin;
    int id;
    string name;
    fin.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/students.dat");
    fin >> stud_cnt; fin.ignore();
    studs = new Student[stud_cnt];

    for ( int i=0; i < stud_cnt; i++) {

        fin >> id >> name;
        studs[i].setName(name);
        studs[i].setId(id);
    }
    fin.close();

}

void Students::storeStuds() {
    ofstream fout;
    fout.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/students.dat");
    fout << stud_cnt << endl;
    for ( int i=0; i < stud_cnt; i++) {
        fout << studs[i].getId() << " " <<  studs[i].getName() << endl;
    }
    fout.close();
}

void Enrollments::loadEnrollments(){

    ifstream fin;
    int eid, sid, cid;
    string cname, sname;
    fin.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/enrollments.dat");
    fin >> enroll_cnt; fin.ignore();
    enroll_list = new Enrollment[enroll_cnt];

    for ( int i=0; i < enroll_cnt; i++) {

        fin >> eid >> cname >> sname >> sid >> cid;
        enroll_list[i].setEnID(eid);
        enroll_list[i].setCourse_ID(cid);
        enroll_list[i].setCName(cname);
        enroll_list[i].setSname(sname);
        enroll_list[i].setStudID(sid);
    }
    fin.close();

}

void Enrollments::saveEnrollments() {
    ofstream fout;
    fout.open("/Users/devintripp/Desktop/swift projects/Hw2/Hw2/enrollments.dat");
    fout << enroll_cnt << endl;
    for ( int i=0; i < enroll_cnt; i++) {
        fout << enroll_list[i].getEnId() << " " <<  enroll_list[i].getCourse_ID() <<  " " << enroll_list[i].getCName() << " " << enroll_list[i].getSName() << " " << enroll_list[i].getStudID();
    }
    fout.close();
}
//
//类.cpp
//Hw2
//
//由Devin Tripp于2018年2月28日创建。
//版权所有©2018 Devin Tripp。版权所有。
//
#包括
#包括
#包括
#包括
#包括“Classes.hpp”
#包括
使用名称空间std;
int Students::getstud_cap(){
返回螺柱盖;
}
void student::addStudent(){
int-id;
字符串温度;
如果(螺柱碳管==螺柱帽){
学生*临时工;
临时=新学生[鞋钉帽+大块尺寸];
对于(int i=0;i>id;cin.ignore();
printf(“输入名称:”);
cin>>温度;cin.忽略();

cout对象已分配了空间,但您尚未调用其构造函数,因此它们尚未初始化,例如:

A* arrayOfAs = new A[5]; //Allocate a block of memory for 5 objects
for (int i = 0; i < 5; ++i)
{
    //initialize an object in memory address provided by the pointer
    new (&arrayOfAs[i]) A();
}

不是你的解决方案,但是你的数组放大方法很奇怪。通常你会根据需要使用
realloc
动态放大数组。你是说我在哪里创建临时数组来存储旧数组数据,然后删除旧数组,然后将临时数组分配给新数组?是的,但我也注意到了你的问题,我很抱歉回答:)这就是我们的指导老师所做的。@GeoffreyOh好的,谢谢!@GeoffreyOperator
new[]
调用新数组中所有元素的默认构造函数。因此答案顶部的放置
new
循环将泄漏内存。初学者甚至不应该在
new[]
delete[]上捣乱
一点也不。我会在类定义中初始化它们吗?我不知道“它们”是什么。但我们不要在这里的评论中讨论它。我会发布一个答案。你可以使用标准容器,还是必须使用
new[]
delete[]
?我必须使用新的和delete@jiveDadson我更新了courses类,尝试像第一个答案所说的那样初始化数组,但它仍然给我相同的错误
A* arrayOfAs = new A[5]; //Allocate a block of memory for 5 objects
for (int i = 0; i < 5; ++i)
{
    //initialize an object in memory address provided by the pointer
    new (&arrayOfAs[i]) A();
}
#include <vector>

typedef std::vector<Student*> Students;
Students studs;

// add an item
Student * student = new Student();
studs.push_back(student);

// remove an item
Student * student = studs.pop_front();
delete student;

// iterate the items
for(Students::iterator it = studs.begin(); it != studs.end(); ++it)
{
  Student * student = *it;
  student->doSomething();
}