Home  >  Q&A  >  body text

c++ for循环中的struct为什么在当前循环结束后没有被释放?

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。都可以在当前循环结束释放,只有上述方法不行。。。。
求解。。。

黄舟黄舟2765 days ago666

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:23:58

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:23:58

    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.

    reply
    0
  • Cancelreply