Ato*_*mix 0 c++ memory-leaks memory-management vector
由指示的线引起的内存泄漏."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
};
Run Code Online (Sandbox Code Playgroud)
这不是内存泄漏
pendingSendReqs.push_back(&f);
Run Code Online (Sandbox Code Playgroud)
这是未来未定义的行为.您正在存储本地变量的地址.任何尝试取消引用函数范围之外的其中一个指针的尝试都是未定义的行为.
你必须问自己是否真的需要一个指针向量.如果你不知道答案,很可能你没有.