我遇到了一个问题,即我无法正确释放内存。我有一个
int*
类型的向量并且
分配内存并将这些指针添加到我的向量后,我只想释放内存并结束程序。
std::vector<int*> students;
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
for (const auto& student : students) {
delete student;
}
students.clear();
_CrtDumpMemoryLeaks();
但是,我从 Visual Studio 2022 中得到以下输出:
Detected memory leaks!
Dumping objects ->
{170} normal block at 0x000001C4AAE05BF0, 72 bytes long.
Data: <# # > 23 81 00 00 00 00 00 00 23 81 00 00 00 00 00 00
{157} normal block at 0x000001C4AAE11E80, 16 bytes long.
Data: < u: > C8 F5 75 3A AF 00 00 00 00 00 00 00 00 00 00 00
Object dump complete.
我就是不明白。首先,我遇到了比这个更复杂的项目(项目由类和其他东西组成)这个问题,我认为内存泄漏的问题可能是在析构函数或 idk 中的某个地方,但是.. idk ...... 附注为了检测内存泄漏,我使用 crtdbg.h
请帮助我正确地释放内存
我假设您的
vector
测试代码是在您最后调用 _CrtDumpMemoryLeaks()
的同一函数中编写的。
vector
保证仅在析构函数中释放其内部内存,当它超出范围时会调用析构函数。
将测试代码移至单独的函数中,您将观察到没有泄漏:
#include <vector>
void test()
{
std::vector<int*> students;
students.push_back(new int);
students.push_back(new int);
students.push_back(new int);
// ...
for (const auto& student : students) {
delete student;
}
students.clear();
} // here the vector's destructor will be called and release the internal momory
int main() {
test();
_CrtDumpMemoryLeaks();
}
旁注:除了教育目的之外,将
int*
存储在 vector
中并不是一个好的做法。如果您想保留“null”/空选项,请存储 int
或 std::optional<int>
。