为什么我的代码包含错误分段错误(核心转储)?

Why does my code contain the error segmentation fault(core dumped)?

本文关键字:错误 核心 转储 分段 我的 代码 包含 为什么      更新时间:2023-10-16

我正在使用指针为图形实现一个C ++程序。 这是代码:


#include <iostream>
#include <sstream>
using namespace std;
// Data structure to store Adjacency list nodes
struct Node {
string source,destination;
int cost;
Node* next;
};
// Data structure to store graph edges
struct Edge {
string src, dest;
int weight;
Edge* edge;
};
class Graph
{
// Function to allocate new node of Adjacency List
Node* getAdjListNode(string src, string dest, int weight, Node* head)
{
Node* newNode = new Node; //create and allocate node
newNode->source = src;
newNode->destination = dest;
newNode->cost = weight;
// set next of new node as head
newNode->next = head;
//move the head to point to the new node
head = newNode;
return newNode;
}
int N;
int n; // number of nodes in the graph
public:
// An array of pointers to Node to //represent
// adjacency list
Node **head;
// Constructor
Graph(Edge edges[], int e, int v)
{
int N=5;
int n=5;
// allocate memory
//Edge *head;
head = new Node*[N];
this->N = N;
// initialize head pointer for all vertices
for (int i = 0; i < N; i++)
head[i] = nullptr;
// add edges to the directed graph
for (int i = 0; i < n; i++)
{
string src = edges[i].src;
string dest = edges[i].dest;
int weight = edges[i].weight;
// insert in the beginning
Node* newNode = getAdjListNode(src, dest, weight, head[i]);
// point head pointer to new node
head[i] = newNode;
}
}
// Destructor
~Graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
// print all neighboring vertices of given vertex
void printList(Node* ptr)
{
while (ptr != nullptr)
{
cout << "(" << ptr->from << ", " << ptr->to
<< ", " << ptr->cost << ") ";
ptr = ptr->next;
}
cout << endl;
}
// Graph Implementation in C++ without using STL
int main()
{
// array of graph edges as per above diagram.
Edge edges[] =
{
// (x, y, w) -> edge from x to y having weight w
{ "aaa","bbb",7 }, { "aaa","ccc",12 }, { "bbb","ddd",9 }, { "eee","ddd",1 },
{ "eee","ccc",14 }
};

// Number of vertices in the graph
int N = 5;
// calculate number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
Graph graph(edges, n, N);
// print adjacency list representation of graph
for (int i = 0; i < N; i++)
{
// print all neighboring vertices of vertex i
printList(graph.head[i]);
}
return 0;
}

我设法运行代码并获得所需的输出,但出现错误,分段错误(核心转储(进程以代码 139 退出。 从我所读到的内容来看,这与非法指针访问有关,但我仍然无法完全确定这里的错误。 谁能帮我? 谢谢。

您正在使用delete[]作为分配了new的指针。这里

~Graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}

应该是

~Graph() {
for (int i = 0; i < N; i++)
delete head[i];
delete[] head;
}

delete应为分配new时,应使用delete[]分配时应使用new[]