【问题标题】:C++ dynamic memory leaksC++ 动态内存泄漏
【发布时间】: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


【解决方案1】:

您的部分问题是您正在分配已分配对象的成员。如果您刚刚拥有,您的代码会更简单:

struct estructura
{
    char algo[100];
    double algo2;
    estructura *next;
};

这样,new estructura 会为您提供所需的完整结构,然后delete current 是您唯一需要做的事情。此外,如果您将新成员添加到 estructura,则一切正常,您不必担心添加另一个 new/delete 对。

【讨论】:

  • 使用 std::string 更好
  • 所以你的意思是分配一个已分配对象的成员,除了不被推荐之外,会代表泄漏吗?这是我不太清楚的部分。
【解决方案2】:

您删除了结构字段,但您确实忘记了删除结构实例。而且,您创建列表的效率非常低。当它可以在 O(n) 中完成时,你在 O(n^2) 中完成。

【讨论】:

  • 是的,我知道,只是简单总结一下思路,这里的思路不是优化而是我对内存泄漏的怀疑。不过,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-11
  • 2017-08-11
  • 1970-01-01
  • 2013-11-28
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多