动态内存分配缓解触发器问题

时间:2020-07-19 08:22:54

标签: c++ triggers

当我尝试在代码末尾释放2个动态内存分配时,触发问题已弹出。我假设我设置了非特定的数组,所以编译器可能会定义要释放的内存更大。

如何正确修改这两行 delete [] msgs; delete [] imageFile; ? 这是代码

#include <iostream>
#include <string>

using namespace std;

class Image {
public:
    operator string() {
        return "사진";
    }
};

class Msg {
public:
    Msg(int sendTime, string sendName) {
        this->sendTime = sendTime;
        this->sendName = sendName;
    }
    int GetSendTime() const { return sendTime; }
    string GetSendName() const { return sendName; }
    virtual string GetContent() const { return""; } 

protected:
    int sendTime;
    string sendName;
};

class Text_Msg : public Msg {
public:
    Text_Msg(int sendTime, string sendName, string text) : Msg(sendTime, sendName) {
        this->text = text;
    }
    string GetContent() const { return text; }

private:
    string text;
};

class Image_Msg : public Msg {
public:
    Image_Msg(int sendTime, string sendName, Image* image) :Msg(sendTime, sendName) {
        this->image = image;
    }
    string GetContent() const { return (string)*image; } 
private:
    Image *image;
};

void printMsg(Msg &m) { 
    cout << "(" << m.GetSendTime() / 100 << ":" << m.GetSendTime() % 100 << ") "; 
    cout << m.GetSendName() << " - "; 
    cout << m.GetContent() << endl;  
}

int main() {

    Image* imageFile[] = {
        new Image(),
        new Image(),
        new Image()
    };
    Msg* msgs[] = { 
    new Text_Msg(1230, "성훈", "안녕, 우리 강아지 사진 보내줄게 !"),
    new Image_Msg(1231, "성훈", imageFile[0]),
    new Image_Msg(1231, "성훈", imageFile[1]),
    new Image_Msg(1231, "성훈", imageFile[2]),
    new Text_Msg(1232, "민주", "와 진짜 귀엽다!"),
    new Text_Msg(1235, "성훈", "그치! 담에 놀러와~~"),
    new Text_Msg(1237, "민주", "응 안녕~!")
    };

    for (Msg* m : msgs) {
        printMsg(*m);
    };


    delete[] msgs; //Fail Here!
    delete[] imageFile;  //Fail Here! (Trigger Issue occured)
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,数组的每个元素都是指向动态分配的对象的指针,但是数组本身不是动态分配的。

因此,您应该删除delete[]行,并为每个元素使用delete

for for (size_t i = 0; i < sizeof(msgs) / sizeof(*msgs); i++) {
    delete msgs[i];
}
for (size_t i = 0; i < sizeof(imageFile) / sizeof(*imageFile); i++) {
    delete imageFile[i];
}