gpt4 book ai didi

c++ - 在递归中使用引用会导致内存泄漏?

转载 作者:行者123 更新时间:2023-11-30 05:27:44 25 4
gpt4 key购买 nike

<分区>

Minimal, Complete, and Verifiable example.

#include <vector>
#include <string>
#include <iostream>
using namespace std;

class node
{
public:
vector<int> node_connections;
string content;
};



int find_remaining_paths(node & a) //reference causing crash
{
for (int i = 0; i < a.node_connections.size(); i++)
{
if (a.node_connections[i] != -1) //if not visited
{
a.node_connections[i] = -1; //path marked as visited
return i; //return index in nodes
}
}
return -1; //no paths remaining
}

void find_euler_circuits(vector<node> & nodes, node & a)
{
cout << a.content << " ";
int temp = find_remaining_paths(a); //finds next path in vector, if one exists
if (temp+1) //if there's a remaining path in node a
{
find_euler_circuits(nodes, nodes[a.node_connections[temp]]); //crashes here
}
return;
}



int main()
{
vector<node> nodes;

node a; //nodes[0]
node b; //nodes[1]
node c; //nodes[2]
node d; //nodes[3]

a.content = "a";
b.content = "b";
c.content = "c";
d.content = "d";

a.node_connections.push_back(1); // a --> b
a.node_connections.push_back(3); // a --> d
b.node_connections.push_back(2); // b --> c
c.node_connections.push_back(0); // c --> a

nodes.push_back(a);
nodes.push_back(b);
nodes.push_back(c);
nodes.push_back(d);

find_euler_circuits(nodes, nodes[0]); // a is starting node
}

我试图在多重图中找到所有欧拉路径。在这种情况下使用节点来表示顶点。这是想法:

例如:

nodes[0] holds node a
nodes[1] holds node b
nodes[2] holds node c
nodes[3] holds node d


Connections:

a --> b
a --> d
b --> c
c --> a

所以节点 'a' 包含索引整数 1,3 (b,d)

节点 'b' 持有索引整数 2 (c)

节点 'c' 持有索引整数 0 (a)

使用递归,程序跨越图:

(a[0] = b) -> (b[0] = c) -> (c[0] = a) -> (a[1] = d)

(我知道这个方法找不到欧拉路径,但我必须先让它工作)

逻辑本身工作正常,如果我删除引用然后它就永远循环 a[0] -> b[0] -> c[0] -> a[0] -> 等等,但是到达

后它立即崩溃的引用
find_euler_circuits(nodes, nodes[a.node_connections[temp]]);

谁能告诉我为什么会导致上述程序出现段错误?导致它崩溃的引用在

int find_remaining_paths(node & a)   //loops forever without &, crashes with &

此外,递归应该在到达一个没有剩余路径的节点时立即停止,但这不是问题所在,因为它在访问一个节点后崩溃

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com