繁体   English   中英

由向量结构引起的C ++内存泄漏

[英]c++ memory leak caused by vector of structs

由指示的行引起的内存泄漏。 “ pendingSendReqs.push_back(&f);” 在sendreq()方法中。 我是C ++的新手,所以我似乎无法弄清为什么发生内存泄漏。 泄漏的内存大小为16个字节。

class Station {
    struct Frame {
        enum { Token, Data, Ack } type;                  // type of frame
        unsigned int src;                                // source id
        unsigned int dst;                                // destination id
        unsigned int prio;                               // priority
    } frame;

    unsigned int stnId;
    static unsigned int requests;                        // total send requests (if needed)
    void data( Frame frame );                            // pass frame
    void main();                                         // coroutine main
    Station *nextStation;
    vector<Frame*> pendingSendReqs;
  public:
    Station( unsigned int id ) : stnId(id) { }
    ~Station() {
        for (int i = 0; i < pendingSendReqs.size(); i++) {
            delete pendingSendReqs.at(i);
            cout << "~: " << pendingSendReqs.at(i) << endl;
        }
    }
    //unsigned int getId() { return stnId; }
    void setup( Station *nexthop ) {                     // supply next hop
        //*nexthop is the object
        nextStation = nexthop;
        //cout << "size: " << sizeof(*nexthop) << endl;
    }
    void sendreq( unsigned int round, unsigned int dst, unsigned int prio ) { // store send request
        Frame f;
        f.type = Frame::Data;
        f.src = stnId;
        f.dst = dst;
        f.prio = prio;


        pendingSendReqs.push_back(&f); //MEMORY LEAK CAUSED BY THIS LINE
    }
    void start();                                        // inject token and start
};

这不是内存泄漏

pendingSendReqs.push_back(&f); 

这是未来的不确定行为。 您正在存储局部变量的地址。 取消引用函数范围之外的那些指针之一的任何尝试都是未定义的行为。

您必须问自己是否真的需要一个指针向量。 如果您不知道答案,很可能您不知道。

您将在矢量内存储指向局部变量的指针,该变量将自动被销毁。 这是非法的。

 vector<Frame*> pendingSendReqs;
 // this is a vector of pointers to struct and not a vector of structs

void sendreq( unsigned int round, unsigned int dst, unsigned int prio ) {
    Frame f;     // this automatic variable will get destroyed when sendreq returns
    f.type = Frame::Data;
    f.src = stnId;
    f.dst = dst;
    f.prio = prio;


    pendingSendReqs.push_back(&f); //MEMORY LEAK CAUSED BY THIS LINE
    // because you're going to hold on to this address which will mean
    // nothing when this function returns
}

您打算这样做的方式是:

vector<Frame> pendingSendReqs;

和内部sendreq

pendingSendReqs.push_back(f); // store the object's copy instead of it's address so that it outlives the life of this local

什么时候

void sendreq(unsigned int round,unsigned int dst,unsigned int prio)

结束,

您的向量PatrickSendReqs将包含指向已消除的变量的指针(因为它们是局部变量),并且将包含垃圾,并会导致崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM