内存泄漏c ++动态数组

时间:2017-07-16 18:59:06

标签: c++ arrays dynamic

你可以帮我理解以下内容:

似乎我有内存泄漏,我想我不能用动态数组做正确的事情。但是我读到我应该删除,但它没有帮助。当我打印值时,前190个是0,有些值没有意义,最后200个值是正确的。这是我的代码的一部分:

在标题文件中:

#define PATH "filespath/"

class Class1
{
public:
    Class1(void);
    ~Class1(void);


    void clean();
    int myfunction(std::string file);
    int SetQC(std::string file);
};

主cpp文件是:

Class1::Class1(void)
{
}

Class1::~Class1(void)
{
}

int Class1::myfunction(std::string file) {

    string Logfile;
    bool found = false, SetFound = false;

    Logfile = PATH + file + ".log";
    std::ifstream f;
    std::string line;
    int offset;
    size_t pos;
    int AVGInt = 0, MaxInt = 0, setInt = 0;
    std::string SetVolumeEnd = "keyword"; // test variable to search in file
    int cntProtocol = 0, cntLine = 0, cntAvgTime = 0, cntMaxTime = 0, cntSetTime = 0, cntSetTimeBad = 0;
    int* SetArray = NULL;
    size_t newSizeVolumeSet = 0;
    f.open(Logfile);

    if (!f){
        std::cout << "Unable to open file " << Logfile << " , please check that the path and the filename is correct." << endl;
        exit(1);
    }
    else{
        std::cout << "File: " << Logfile << " loaded correctly" << endl;
    }

    if (f.good()){
        while (std::getline(f, line)) { // line is the whole line 
            cntLine++;
                pos = line.find(SetVolumeEnd);
                if (pos != string::npos) // string::npos is returned if string is not found
                {
                    SetFound = false;
                    string SetTime = line.substr(line.length() - 10, 10);
                    pos = SetTime.find("=");
                    string SetTimeExtract = SetTime.substr(pos + 1, SetTime.length() - pos - 3);
                    setInt = stoi(SetTimeExtract);

                    newSizeVolumeSet = cntSetTime + 1;
                    SetArray = new int[newSizeVolumeSet];
                    SetArray[cntSetTime] = setInt;
                    std::cout << "SetArray[" << cntSetTime << "] = <" << SetArray[cntSetTime] << "> ms." << endl;
                    delete[] SetArray;
                    cntSetTime++;
                }
            }
        for (int j = 0; j < cntSetTime; j++){
            cout << j << " element : " << SetArray[j] << endl;
        }
        f.close();
    }

    ofstream set;
    string sett = PATH + file + "set.txt";
    set.open(sett);
    for (int k = 0; k < cntSetTime; k++){
        set << k << " element : " << SetArray[k] << "\n";
    }
    set.close();
    }

0 个答案:

没有答案