指针不规范,wntdll

本文探讨了在`LinkQueue`类的`pop`方法中,忽视更新`front->next`可能导致的指针悬挂问题。通过实例和修复后的代码,强调了在操作链表时更新指针的重要性,防止空悬指针引发的错误和资源浪费。
摘要由CSDN通过智能技术生成

记录一下,不好好使用指针的坏处

void LinkQueue<ElemType>::pop(ElemType& e)
{
	if (!Empty()&&front->next!=rear)
	{
		node<ElemType>* tem = front->next;
		e = tem->data;
		front->next = tem->next;
		delete tem;
	}
	else if (!Empty() && front->next == rear)
	{
		e = rear->data;
		delete rear;
		//front->next = nullptr;
		rear = front;
	}
	else
	{
		cout << "队列空" << endl;
	}
}

初看,是不是没毛病,但是,,有一个非常可怕的事,就是第二个if中,当我们释放了rear后,front->next还指向rear,这个就很不好了,因为这个rear这个指针已经被释放掉了,也就是不更新front->next为nullptr,那么就会导致后面错误的判空,继而引用已经原地去世了的rear指针。

所以无论什么时候,一定要,一定要记得更新front->next

下面给出一个安全的一批还简单的版本

void LinkQueue<ElemType>::pop(ElemType& e)
{
	if (!Empty())
	{
		node<ElemType>* tem = front->next;
		e = tem->data;
		front->next = tem->next;
		if (tem == rear)
		{
			rear = front;
		}
		delete tem;
	}
	else
	{
		cout << "队列空" << endl;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

thoroughly strive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值