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。都可以在当前循环结束释放,只有上述方法不行。。。。
求解。。。
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 nextListNode l1(i)
. In the end, the next of9
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.