【发布时间】:2023-03-25 02:08:01
【问题描述】:
所以我有这个问题,我目前正在学习如何获取动态内存以在堆中分配变量(在 C++ 上),所以我只是创建一个结构并在其上放置一些项目,然后在 deleteList(estructura * ) 函数我删除所有变量,问题是我分配了大量内存,因此泄漏。
struct estructura
{
char *algo;
double *algo2;
estructura *next;
};
estructura* lastEstructura(estructura *head)
{
estructura *current = head;
while (current -> next)
{
current = current -> next;
}
return current;
}
void crearLista(estructura *head)
{
for (int i = 0; i < 8200; i++)
{
estructura *current = new estructura;
current -> algo = new char[100];
current -> algo2 = new double;
current -> next = nullptr;
estructura *temp = lastEstructura(head);
temp -> next = current;
}
}
void deleteList(estructura *head)
{
estructura *current = head;
while (current) {
estructura *temp = current;
current = current -> next;
delete [] temp -> algo;
delete temp -> algo2;
temp -> next = nullptr;
delete temp;
}
}
int main(int argc, const char * argv[])
{
int i = 0;
cout << "enter: ";
cin >> i;
do {
estructura *head = new estructura;
head -> algo = new char[100];
head -> algo2 = new double;
head -> next = nullptr;
crearLista(head);
deleteList(head);
cout << "enter: ";
cin >> i;
} while (i == 1);
return 0;
}
我真的很想了解这一点,为什么会出现这种泄漏,所以请有人帮助我,我已经尝试过搜索,但没有找到可以帮助我的东西。 (我对 C++ 比较陌生)
【问题讨论】:
-
您可以通过将程序更改为使用
std::string而不是char* algo和类似的方式来为自己省去很多麻烦。另外,为什么要使用循环分配 8200 个列表元素? -
一旦你学会了标准库(std::string, std::vector ...),你就不再需要费力地做事了。当然,到那时您将不会实现自己的链表,而是使用标准库来实现。此外,如果你真的需要使用新的 std::unique_ptr 和 std::shared_ptr 也会让你摆脱这个问题。
-
使用调试器/valgrind,但不要在这里问第一。
-
“巨大的内存量”是多少?我在这里看不到任何看起来会导致泄漏的东西。
-
在我在这里读到的所有内容中,你为什么认为你有内存泄漏?你的程序使用内存是正常的。当它终止而没有释放它新的所有东西时,就是有泄漏的时候。是否有工具告诉您这是一个问题,还是您只是怀疑它?
标签: c++ pointers memory memory-leaks