动态内存是否与全局变量相当?

时间:2015-11-21 19:13:17

标签: c++ data-structures linked-list

链接列表中,我们声明, 73, 75), (76, 86, 91), (42, 91, 92), (8, 54, 71), (11, 54, 87), (37, 79, 86), (2, 17, 32), (44, 67, 78), (14, 24, 56), (10, 64, 79), (9, 90, 94), (39, 52, 88), (62, 78, 90), (9, 60, 71), (23, 25, 30), (5, 27, 92), (33, 74, 78), (68, 70, 84), (48, 79, 95), (8, 70, 95), (23, 68, 78), (14, 45, 78), (8, 36, 73), (72, 86, 88), (13, 26, 74), (35, 60, 86), (3, 29, 76), (6, 15, 74), (46, 54, 73), (7, 41, 88), (48, 59, 90), (23, 30, 73), (71, 83, 91), (42, 78, 96), (44, 60, 92), (27, 46, 68), (27, 72, 88), (34, 74, 78), (24, 55, 93), (84, 93, 97), (32, 36, 73), (7, 31, 38), (28, 43, 66), (29, 37, 40), (19, 33, 96), (45, 66, 77), (25, 66, 72), (22, 60, 74), (59, 60, 76), (30, 57, 82), (11, 16, 51), (41, 48, 99), (5, 21, 86), (18, 27, 98), (26, 34, 95), (19, 72, 74), (32, 34, 35), (43, 68, 93), (36, 57, 77), (20, 50, 90), (25, 71, 99), (47, 74, 87), (9, 26, 35), (20, 24, 89), (27, 67, 83), (3, 19, 70), (20, 72, 79), (24, 36, 79), (8, 25, 43), (49, 53, 87), (24, 63, 68), (21, 63, 92), (21, 56, 72), (26, 43, 87), (79, 92, 94), (22, 41, 98), (45, 55, 88), (30, 46, 94), (38, 71, 79), (17, 51, 81), (43, 65, 97), (40, 56, 72), (19, 62, 88), (31, 38, 98), (15, 25, 79), (24, 45, 71), (52, 87, 98), (20, 39, 82), (23, 33, 44), (43, 68, 88), (6, 8, 29), (36, 73, 95), (48, 78, 84), (22, 38, 84), (21, 65, 97), (30, 31, 57), (27, 28, 38), (2, 33, 46), (24, 29, 51), (4, 6, 45), (64, 71, 93), (14, 36, 68), (36, 51, 62), (20, 40, 68), (19, 71, 81), (33, 60, 81), (13, 25, 60), (17, 39, 68), (68, 69, 81), (18, 19, 89), (2, 28, 61), (4, 67, 71), (12, 26, 52), (34, 41, 46), (22, 27, 59), (28, 56, 96), (1, 25, 53), (39, 61, 90), (11, 31, 44), (17, 40, 82), (16, 21, 73), (19, 78, 93), (10, 16, 36), (21, 30, 32), (15, 23, 69), (9, 21, 28), (20, 29, 40), (11, 48, 61), (36, 71, 81), (19, 24, 48), (7, 49, 61), (15, 74, 99), (13, 45, 85)]) ,如下所示:

node

我们的插入函数看起来像这样

struct node
{
    int data;          // Data part
    struct node* next; // pointer to next node

    node(int key)
    {
        data = key;
        next = NULL;
    } 
};

如果函数void insert(int key) { struct node* go = head; // Head is global. while(go != NULL) { go = go -> next; } go -> next = new node(key); } 实际上正在返回insert,那么它如何才能对链表进行更改呢?

运算符void(来自免费商店)分配的内存是否像全局变量一样?

1 个答案:

答案 0 :(得分:2)

new不像全局变量。在C ++中,全局变量(假设你不是在讨论全局指针)是在你的应用程序入口点之前分配的,它是“main”被调用并在你的应用程序关闭时释放。

另一方面,

new在调用delete时调用和解除分配时分配新内存

MyClass* c = new MyClass(); // Allocate
// ..
delete c; // Deallocate, MyClass c is deleted

因此,如果您使用new创建一些对象,并且永远不会删除它。它将始终存在,但您可能会丢失指向所分配数据的指针并导致内存泄漏。