c++ for循环中的struct为什么在当前循环结束后没有被释放?
黄舟
黄舟 2017-04-17 15:21:58
0
2
688
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

for(int i=0;i<10;i++)
{
    ListNode l1(i);
    //此处将l1添加到链表中
}

这样的写法却会导致最后的链表结果全为9,也就是说虽然每一次都是将指针指向l1但是循环中l1从来没有被释放过。。。这是为什么?
我尝试过malloc和new。都可以在当前循环结束释放,只有上述方法不行。。。。
求解。。。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
Peter_Zhu

Local variables will pop off the stack after leaving the statement block. ListNode l1(i)They will be released every time. This is actually very dangerous. The reason why there is no crash is because your logic is simple. The memory space released last time is filled back by the next ListNode l1(i). In the end, the next of 9 points to itself.

new and malloc do not allocate memory on the stack, so they will not be released automatically.

刘奇

Because l1 is on the stack and is at the same address in each loop, the later values ​​will overwrite the previous ones. new should be used here.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template