C ++动态内存泄漏

时间:2014-11-26 17:19:32

标签: c++ pointers memory memory-leaks

所以我有这个问题,我正在学习如何获得动态内存来在堆中分配变量(在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 ++比较陌生)

2 个答案:

答案 0 :(得分:2)

您的部分问题是您正在分配已分配对象的成员。如果您只是:

,您的代码会更简单
struct estructura
{
    char algo[100];
    double algo2;
    estructura *next;
};

这样,new estructura为您提供了所需的完整结构,然后delete current是您唯一需要做的事情。此外,如果您向estructura添加新成员,一切正常,您无需担心添加其他new / delete对。

答案 1 :(得分:0)

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

相关问题