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(未签名的int圆,未签名的int dst,unsigned int prio)
结束,
您的矢量pendingsEndreqs将包含被消除的变量(因为是局部变量),并且将包含垃圾。
相关文章:
- 将结构向量排序为子组
- 访问存储在向量C++中的结构的多态成员
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 将 int 映射到 C++ 中的向量结构
- 如何在 c++ 中的向量结构中使用结构向量
- 无法将值存储到向量结构中
- 无法将.CSV文件读取为代表向量结构的类
- MPI,C,派生类型,向量结构
- 向量结构的打印成员
- 在 c++ 中对向量<结构 S> 进行二分搜索?
- 不需要删除向量<结构A*>
- 在C++中循环向量结构<string>
- 将字符串放入字符串的向量结构中
- 共享内存中的向量结构
- 我的向量结构没有像预期的那样迭代