找不到我的记忆泄漏

时间:2016-12-05 21:35:35

标签: c++

2个问题:

  1. 我在这个程序上运行了valgrind,丢失了大约400字节,但我不知道我做错了什么。
  2. 出于某种原因,在学生对象的第一次(仅第一次)初始化(roster[i]int i = 0),循环只允许我将两个参数传递给我的构造函数。我知道这听起来很奇怪,但第一次循环调用与其他循环不同。
  3. HEADER

    #include<iostream>
    #include<string>
    
    using namespace std;
    
    class Student{
    
    public:
    Student();
    Student(string ln, string fn, string cn) {setLast(ln);setFirst(fn);setCourse(cn);}
    void showInfo(){cout << firstname << " " << lastname << " in " << coursename << endl;} 
    
    protected:
    void setLast (string l){lastname = l;}
    void setFirst (string f){firstname = f;}
    void setCourse (string c){coursename = c;}
    string firstname;
    string lastname;
    string coursename;
    };
    

    MAIN

    int main(){
    
    Student **roster;
    int num;
    cout << "how many?";
    cin >> num;
    roster = new Student*[num];
    string l,f,c;
    
    for (int i = 0; i < num; i++){
      cout << "\nenter last, first, course: ";
      getline(cin, l);
      getline(cin, f);
      getline(cin, c);
      roster[i] = new Student(l, f, c);
      roster[i]->showInfo();
    }
    delete [] roster;
    };
    

1 个答案:

答案 0 :(得分:0)

问题是你正在新建一个数组,并且你正在新建数组中的所有学生。您创建了new Student*[]和一些new Student,但只有delete[] arr,您忘了delete x

在修复之前,我想建议您使用vector和unique_ptr,这样可以首先防止所有错误:

std::vector<std::unique_ptr<Student>> roster;

int num;
cout << "how many?";
cin >> num;
roster.reserve(num);

std::string l,f,c;

for (int i = 0; i < num; i++){
  cout << "\nenter last, first, course: ";
  getline(cin, l);
  getline(cin, f);
  getline(cin, c);

  roster.emplace_back(std::make_unique<Student>(l, f, c));
  roster.back()->showInfo();
}

现在,您的代码的解决方案。你应该把它放在代码的末尾:

for (int i = 0; i < num; i++){
    delete roster[i];
}
delete [] roster;