【发布时间】:2016-08-13 13:02:01
【问题描述】:
我在这个webpage 中使用了 Dijkstra 算法。最近发现如果图中的顶点数超过60000,在将新的边信息作为节点添加到相邻列表中时,系统会响应“core dumped”。
以下是原程序中相邻列表的摘录:
// A structure to represent a node in adjacency list
struct AdjListNode
{
int dest;
int weight;
struct AdjListNode* next;
};
// A structure to represent an adjacency liat
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest, int weight)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
这是图形和添加新边的代码
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
// Initialize each adjacency list as empty by making head as NULL
for (int i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest, int weight)
{
// Add an edge from src to dest. A new node is added to the adjacency
// list of src. The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest, weight);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// Since graph is undirected, add an edge from dest to src also
newNode = newAdjListNode(src, weight);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
供您参考,这是我测试的主要功能
int main()
{
int V = 100000;
struct Graph* graph = createGraph(V);
for(int i=0;i<V/2;i++)
for(int j=i+1;j<V;j++)
addEdge(graph, i, j, i+j);
return 0;
}
【问题讨论】:
-
看来你的内存快用完了,不是吗?
-
这被标记为 C++。使用
std::list或std::forward_list并忘记malloc的东西。即使100,000 nodes 也没有问题。 -
这段代码不是最现代的 c++,我会听从这里给出的建议。尽管如此,该代码没有大问题,也没有理由将其作为链表更快地耗尽内存。我会把钱赌在创建图表的代码中的错误上,但我们在这里看不到它(所以请添加它!)
-
所有贴出的代码都是C代码,不是C++代码。如果您使用 C,则应将其标记为 C,而不是 C++。
标签: c++ c algorithm memory-management