map/set 中的 insert(new ClassObject) 内存泄漏

Memory Leaks with insert(new ClassObject) in map/set

我正在尝试在 mapset 中插入新的 class 对象“Student”(每个容器都有不同的学生块) .为此,我使用 insert() 函数,如下所示:

// Map:
M.insert({ tempID, new Student(tempID, nameTemp, addressTemp, phoneTemp, numClassesTemp, gpaSumTemp) });

// Set:
S.insert(new Student(tempID, nameTemp, addressTemp, phoneTemp, numClassesTemp, gpaSumTemp));

我的代码编译并运行良好,但内存泄漏检查器一直指向这两行。我要在某处使用 delete 吗?在哪里?还是我要在我的 Student 析构函数中包含一些东西?

我拿出一大块代码来演示问题,并将其放在下面的可编译文件中。 (我排除了我的 set 的代码,因为我相信我的 map 的代码足以找到内存泄漏的来源):

Student.h:

#pragma once
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <iterator>
#include <algorithm>

using namespace std;

class Student
{
public:
    Student(unsigned long long int ID, string name, string address, string phone, int numClasses, double sum_gpa);
    ~Student();

    unsigned long long int ID;
    string name;
    string address;
    string phone;
    int numClasses;
    double gpaSum;

    string getGPA();
    string toString();
};

Student.cpp:

#include "Student.h"


Student::Student(unsigned long long int ID, string name, string address, string phone, int numClasses, double gpaSum)
{
    this->ID = ID;
    this->name = name;
    this->address = address;
    this->phone = phone;
    this->numClasses = numClasses;
    this->gpaSum = gpaSum;
}


Student::~Student()
{
}

string Student::getGPA(){
    string getGPA;
    stringstream ss;

    if (numClasses == 0){
        getGPA = "0.00";
    }
    else{
        ss << fixed << setprecision(2) << gpaSum / numClasses;
        ss >> getGPA;
    }

    return getGPA;
}

string Student::toString(){
    string toString;
    stringstream IDss;
    stringstream GPAss;
    string IDstr = "";
    string GPAstr = "";

    IDss << ID;
    GPAss << getGPA();
    IDss >> IDstr;
    GPAss >> GPAstr;

    toString += IDstr; toString += "\n"; toString += name; toString += "\n";
    toString += address; toString += "\n"; toString += phone; toString += "\n";
    toString += GPAstr;

    IDss.clear();
    GPAss.clear();
    return toString;
}

GPA.h(GPA.h/cpp 是 map/set-related 函数所在的位置):

#include "Student.h"

class GPA
{

public:
    GPA();
    ~GPA();

    map<unsigned long long int, Student*> M;

    bool importStudents(string setFileName);
    void clear();
    int lineCounter(string fileName);
};

GPA.cpp

#include "GPA.h"

GPA::GPA()
{
}

GPA::~GPA()
{
}

bool GPA::importStudents(string mapFileName){
    fstream mapFile(mapFileName);

    /** vvv START: ERROR CHECKING vvv */
    /* Check for Invalid File(s)*/
    if (!mapFile){
        mapFile.close();
        return false;
    }
    mapFile.close();

    /* Check for Incorrect Line Count for Files */
    if (lineCounter(mapFileName) % 4 != 0){
        return false;
    }
    /** ^^^ END: ERROR CHECKING ^^^ */

    /** vvv START: IMPORT TO MAP vvv */
    mapFile.open(mapFileName);
    if (mapFile.is_open()){
        unsigned long long int tempID = 0;
        string dummySpace = "";
        string nameTemp = "EMPTY";
        string addressTemp = "EMPTY";
        string phoneTemp = "EMPTY";
        int numClassesTemp = 0;
        double gpaSumTemp = 0;
        while (mapFile >> tempID){
            getline(mapFile, dummySpace);
            getline(mapFile, nameTemp);
            getline(mapFile, addressTemp);
            getline(mapFile, phoneTemp);

            M.insert({ tempID, new Student(tempID, nameTemp, addressTemp, phoneTemp, numClassesTemp, gpaSumTemp) });
            cout << M.at(tempID)->toString() << "\n\n";
        }
    }
    /** ^^^ END: IMPORT TO MAP ^^^ */

    return true;
}

void GPA::clear(){
    for (map<unsigned long long int, Student*>::iterator it = M.begin(); it != M.end(); ++it){
        Student* m = it->second;
        delete m;
    }
        M.clear();
}

int GPA::lineCounter(string fileName) {
    std::ifstream myfile(fileName);

    // new lines will be skipped unless we stop it from happening:    
    myfile.unsetf(std::ios_base::skipws);

    // count the newlines with an algorithm specialized for counting:
    unsigned line_count = std::count(
        std::istream_iterator<char>(myfile),
        std::istream_iterator<char>(),
        '\n');

    return line_count;
}

Main.cpp:

#include "GPA.h"

using namespace std;

int main(){
    GPA myGPA;

    myGPA.importStudents("studentListMap_Small.txt");
    myGPA.importStudents("studentListMap_Large.txt");
    myGPA.clear();

    return 0;
}

studentListMap_Small.txt:

020961797
Joshua Cooper
0509 McCrooke Avenue, Columbus, California 52826
552-534-8671
283385788
Yazan Halawa
6707 Law Street, Madison, Alaska 01322
351-385-5237
322058308
Adam Fudge
1395 Department Street, Raleigh, Arizona 34983
287-570-5987
011812277
Paul Gibby
0940 Venice Street, Concord, Delaware 18729
779-320-4502

studentListMap_Large.txt:

105396824
Justin Roberts
9459 Barn Street, Bismarck, Illinois 80517
739-784-0853
760491717
Marcus Tanner
3493 Mill place, Atlanta, Virginia 96801
227-268-5713
417607834
Meza Rodolfo Amaya
8345 Dean Avenue, Albany, New Mexico 22539
596-579-2033
125363151
Paul Thornton
5944 Prague Avenue, Montpelier, Ohio 06867
181-920-3767
978344395
Brett Turley
2780 Jameson's Crossing, Frankfort, Rhode Island 55970
419-435-4046
850843037
Evan Bradham
8356 Venice Street, Raleigh, Pennsylvania 11096
573-496-1240
921190591
Sam Duzett
0767 Delaware Avenue, Jefferson City, South Dakota 48720
516-295-0387
870255828
Nathaniel Merrill
0776 P. Auerbach Avenue, Lincoln, South Carolina 59051
703-933-0882
819890357
Mark Solocinski
9900 Flower Avenue, Sacramento, Washington 09677
613-592-1728
020961797
Joshua Cooper
0509 McCrooke Avenue, Columbus, California 52826
552-534-8671
283385788
Yazan Halawa
6707 Law Street, Madison, Alaska 01322
351-385-5237
322058308
Adam Fudge
1395 Department Street, Raleigh, Arizona 34983
287-570-5987
011812277
Paul Gibby
0940 Venice Street, Concord, Delaware 18729
779-320-4502
716843573
Fridrich Perez
7656 Bay Avenue, Annapolis, Maryland 20056
469-205-9082
634930318
Michael Douglas
5575 Southern Abby Avenue, Springfield, Georgia 68675
135-483-5225
192066959
Michelle Stevens
6698 Southern Abby Avenue, Columbia, Illinois 70022
887-493-1163
741281027
Jesse Millar
7968 Museum Avenue, Des Moines, Montana 33359
084-086-9848
091487171
Sam Zamora
3657 Newhaven Avenue, Oklahoma City, Pennsylvania 32206
900-392-2156
919403007
Mark Petersen
5858 Walden Alley, Harrisburg, Louisiana 00923
802-942-4624
432610620
Chase Lundell
6721 Central cesta, Helena, Kansas 64600
300-892-2067
038218766
Ryan Bullock
7125 Eppink Square, Indianapolis, Oregon 83838
720-648-3033
207448181
Oliveros Isai Mercado
1910 King Arthur I street, Lansing, Illinois 09861
340-027-8892
578873248
Minh Do
4467 Shopping Avenue, Atlanta, Idaho 46028
489-286-6549
286617977
Anthony Constantino
2868 Highway Avenue, Harrisburg, New Mexico 62475
150-412-3674
425049135
Daniel Feller
5350 Wallstreet and, Jefferson City, Ohio 98281
422-317-1595
738936225
Scott Ryvola
7307 Flower Avenue, Pierre, Wyoming 63056
210-827-1370
383308329
David Christenson
3984 Farmer's Lane, Hartford, Florida 55765
433-499-4397
666537985
Jannae Turley
6624 Camp Street, Austin, Montana 47779
474-205-0411
356559266
Michael Kredt
1489 Francis II Street, Bismarck, Tennessee 25004
386-269-4228
535348580
Nathan Radmall
8557 Hazlett Avenue, Atlanta, Massachusetts 44369
742-936-1925
530941737
Elora Salway
8754 Queen Mary Elisabeth Alley, Springfield, Alaska 81279
215-936-2915
441365589
Cody Burt
7738 Pine Street, Carson City, Maryland 51525
407-433-7728
880738319
Mercedes Reuel
4341 Long Road Avenue, Augusta, Tennessee 93916
305-649-3653
212067186
Adam Petersen
4709 Delta Street, Raleigh, South Dakota 30268
233-788-2153
835850757
Josh Humpherys
9020 Dimitri Street, Austin, Missouri 24887
976-602-4146
318093806
Scott Saunders
3353 Jamal Hustrova Street, Santa Fe, Illinois 94000
117-310-0358
398071827
Young Tai Ahn
8528 P. Auerbach Avenue, Richmond, Indiana 38480
261-814-2605
994452189
Cherrez Andres Galan
8562 Theater Street, Boston, Ohio 54016
075-419-3779
409268016
Mat Weaver
5060 Democracy Avenue, Sacramento, South Dakota 98824
494-586-1315
725157853
Cache Staheli
7012 Industry Street, Bismarck, Mississippi 28517
453-814-0513
313757119
Christian Beesley
3126 Hendrix Avenue, Raleigh, Oklahoma 65343
173-132-3679
229435544
Dallin Cox
7264 Federation Avenue, Salem, Tennessee 37878
395-058-1800
670706814
Sam Warnick
4962 Swamp Street, Montpelier, Virginia 28540
956-752-0303
810564069
Marshall Garey
5532 Hospital Street, Harrisburg, Utah 82578
857-706-9850
139697451
Nick Wahlin
7391 Wallstreet and, Boise, Alabama 35351
629-249-0451
647744778
Nicole Viland
3063 McCrooke Avenue, Montpelier, Hawaii 48041
770-835-5060
351953580
Spencer Stock
2949 Storm Alley, Phoenix, Maryland 05300
728-001-4076
685585839
Kyle Brown
4594 Long Road Avenue, Madison, West Virginia 46981
146-275-4304
079800628
Kyle Baker
6311 Monorail Street, Charleston, Indiana 71229
762-043-7717
996857052
Jordon Ritchie
3093 New Orleans Street, Little Rock, New Hampshire 48740
457-081-6324
585472870
Jason Sevey
0405 Beatles Avenue, Charleston, Idaho 96140
829-676-5844
363108475
Sean Miller
6961 Prague Avenue, Sacramento, Louisiana 54034
008-074-9144
595315616
Raphael Pak
0703 Forest Street, Saint Paul, Washington 76921
920-396-7339
420195410
Trevor Savage
2797 Katrina Street, Little Rock, Colorado 16981
371-187-7168
451471400
Trenn Brown
3970 Adelaide Avenue, Harrisburg, Pennsylvania 99190
538-118-5794
562466352
Mackenzie Wilson
2375 Heritage Avenue, Raleigh, North Carolina 17052
489-945-0146
103805170
Samuel Lyons
6205 Mayores Road, Santa Fe, Oklahoma 44576
819-831-2871
017825823
Andrew Mello
4533 Oceana Side-Street, Juneau, New Mexico 76672
250-576-9630
902845517
Landen Barr
7033 Stone Street, Madison, South Carolina 46058
469-236-1694
819361221
Sam Farnsworth
2066 Vienna Street, Harrisburg, West Virginia 45424
412-423-4694
468756954
NATHAN Stout
0576 Maple Street, Atlanta, Mississippi 32910
555-392-3427
222487207
Justin Esplin
2874 Flower Avenue, Providence, Florida 61584
246-972-5978
996718409
Jonathan Hodnett
8498 Sylvania Avenue, Honolulu, Massachusetts 79595
183-590-7272
364801603
Garrett Porter
0732 Oceana Side-Street, Juneau, West Virginia 39951
883-447-9680

memory_leak_report.txt:

http://textuploader.com/5mejr

每个 new 需要一个匹配的 delete

看起来 GPA 是这些对象的所有者,因为它包含 MS,因此您应该在 GPA 的析构函数中删除它们。
您可以通过迭代 MS 以及 deleteing 每个元素来做到这一点。

旁注:您可以替换

fstream mapFile(mapFileName);
mapFile.close();

mapFile.open(mapFileName);

fstream mapFile(mapFileName);

while (mapFile.is_open())
{
    // ...
    mapFile.close();
}

if (mapFile.is_open())
{
    // ...
}

文件流在其生命周期结束时关闭,您无需手动执行此操作。