调用角色移除函数触发Stack Overflow Exception问题求助
栈溢出错误原因排查与解决方法
核心原因
栈溢出的直接诱因是World类的RemoveChar方法无限递归调用自身:
public void RemoveChar(string cName) { RemoveChar(cName); }
该方法没有任何终止条件,每次调用都会在调用栈中新增一个栈帧,持续消耗栈内存,最终触发Stack Overflow Exception。
另外World类维护着Partylist(Node<Party>类型),这个方法的实际逻辑应该是遍历所有派对,调用派对的角色移除方法,而非自调用。
解决步骤
1. 修复World类的RemoveChar方法
修改为遍历所有Party,调用每个Party的RemoveChar方法来移除目标角色:
public void RemoveChar(string cName) { Node<Party> temp = Partylist; // 遍历所有派对 while (temp != null) { temp.GetValue().RemoveChar(cName); temp = temp.GetNext(); } }
2. 修正Party类RemoveChar方法的逻辑问题
原Party的移除方法存在遍历逻辑错误,会导致漏删、空引用异常等问题,修正后的代码如下:
public void RemoveChar(string cName) { // 先处理头节点就是目标角色的情况 while (Characters != null && Characters.GetValue().getName() == cName) { Characters = Characters.GetNext(); } // 如果链表为空,直接返回 if (Characters == null) return; Node<Character> temp = Characters; // 遍历后续节点,查找并移除目标角色 while (temp.HasNext()) { if (temp.GetNext().GetValue().getName() == cName) { // 跳过目标节点,完成移除 temp.SetNext(temp.GetNext().GetNext()); } else { // 仅当未删除节点时移动指针,避免跳过有效节点 temp = temp.GetNext(); } } }
内容的提问来源于stack exchange,提问作者Noam Gaming
相关产品推荐
相关产品推荐

