我有一个非常奇怪的内存泄漏和字符串问题

时间:2018-03-13 15:08:08

标签: c++ memory-leaks

当我分配几乎相同的类但有一个成员变量为字符串而不是整数时,我遇到内存泄漏问题。

带有字符串的类会产生内存泄漏,但不会产生整数。我已经删除了我可以删除的所有内容,但我仍然会得到内存泄漏请帮助。

所以soundbook类给了我内存泄漏我不知道为什么因为我已经分配了任何东西但是当我删除了字符串成员时我不再为内存泄漏而导致这种情况发生了吗?

// main

#include <iostream>

#include "PappersBok.h"
#include "SoundBook.h"

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    Books *bk[5];

    bk[0] = new SoundBook();
    bk[1] = new PappersBok();
    bk[2] = new PappersBok();
    bk[3] = new PappersBok();
    bk[4] = new PappersBok();

    for (int i = 0; i < 5; i++)
    {
        delete bk[i];
    }


    system("pause");

    return 0;
}

// soundbook class .h和.cpp

#ifndef SOUNDBOOK_H
#define SOUNDBOOK_H


#include "books.h"

class SoundBook : public Books
{
private:
    std::string medium;
public:
    SoundBook(std::string title = "?", std::string author = "?", std::string medium = "?");
    ~SoundBook();

    std::string toString() const;
    void setMedium(std::string medium);

};


#endif

//.cpp
#include "SoundBook.h"



SoundBook::SoundBook(std::string title, std::string author, std::string medium)
    :Books(title, author)
{
    this->medium = medium;
}

SoundBook::~SoundBook()
{
}  
std::string SoundBook::toString() const
{
    return ", Medium: " + this->medium;
}

// Pappersbok class .cpp和.h

#ifndef PAPPERSBOK_H
#define PAPPERSBOK_H


#include "books.h"

class PappersBok : public Books
{
private:
    int nrOfPages;
public:
    PappersBok(std::string title = "?", std::string author = "?", int nrOfPages = 0);
    ~PappersBok();

    std::string toString() const;
};

#endif

//。CPP

#include "PappersBok.h"



PappersBok::PappersBok(std::string title, std::string author, int nrOfPages)
    :Books(title, author)
{
    this->nrOfPages = nrOfPages;
}


PappersBok::~PappersBok()
{
}

std::string PappersBok::toString() const
{
    return ", Number of pages: " + std::to_string(this->nrOfPages);
}

1 个答案:

答案 0 :(得分:6)

Any introductory text on polymorphism in C++ will tell you to use a virtual destructor.

Otherwise, delete can't do its job properly when you call it on a base pointer.

bk[0] is a Books* pointing to a SoundBook, but delete doesn't know that it's pointing to a SoundBook, and so cannot fully destroy the members of its derived part. Hence the memory leak (and, more broadly, the program has undefined behaviour).