我在这个webpage中使用Dijkstra算法。最近我发现如果图中顶点的数量超过60000,系统会在将新的边缘信息作为节点添加到相邻列表时以“核心转储”进行响应。
以下是原始程序中相邻列表的摘录:
// 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;
}
答案 0 :(得分:1)
因此,您尝试将近4 * 10 ^ 9个边添加到图中。每个边缘(AdjListNode
- 对象)在64位机器上需要16个字节。我们也谈论至少64GB,这是很多。
然而,malloc(sizeof(struct AdjListNode))
的每次调用都要花费超过16个字节:管理堆上的元素有一些开销,每次内存请求时系统都会超过16个字节。在我的系统上,我需要2GB用于4 * 10 ^ 7个边缘,即大约每条边50个字节。
无论如何,在程序执行的某个时刻你将失去记忆,malloc
将在你的代码的这一部分返回0:
struct AdjListNode* newAdjListNode(int dest, int weight)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
//newNode is NULL if there is no memory!
newNode->dest = dest; //BOOM! segmentation error due to newNode==NULL
....
如您所见,由于NULL指针解除引用,程序将崩溃。
我想对于每个实现,它都有一个问题大小的限制。并且这种实现的限制在4 * 10 ^ 9边缘之下。
至于你的问题:如果你想减少使用内存,你应该避免分配许多不同的对象 - 最好将它们一个接一个地放入一个连续的内存中。对于这个std::vector
是一个很好的选择,如果你使用C ++(但你的代码是纯C)。