【发布时间】:2014-11-28 07:49:27
【问题描述】:
我想存储一个非常大的图(大约 40k 个节点)的邻接矩阵。但是使用 int 和 char 数组,由于内存限制,我遇到了分段错误。使用 malloc 的动态分配在这里也失败了。任何人都可以建议一种使用位图二维数组实现此功能的方法吗? 到目前为止,这是我在 C 中的实现:
#include <stdio.h>
#include <stdlib.h>
int MAX = 50000;
void clustering(char adj[][MAX]);
int count_neighbour_edges(int temp[], int len, char adj[][MAX]);
int main()
{
int nol = 0, i, j, k;
FILE *ptr_file1,*ptr_file2;
struct community
{
int node;
int clust;
};
struct community d;
ptr_file1 = fopen("community.txt","r");
if (!ptr_file1)
return 1;
while(fscanf(ptr_file1,"%d %d",&d.node, &d.clust)!=EOF) //Getting total no. of nodes from here
{
nol++;
}
char adj[nol+1][nol+1]; //Getting segmentation fault here
struct adjacency
{
int node1;
int node2;
};
struct adjacency a;
ptr_file2 = fopen("Email-Enron.txt","r");
if (!ptr_file2)
return 1;
while(fscanf(ptr_file2,"%d %d",&a.node1, &a.node2)!=EOF)
{
adj[a.node1][a.node2] = '1';
adj[a.node2][a.node1] = '1';
}
clustering(adj);
return (0);
}
【问题讨论】:
-
您可能想尝试将矩阵存储在堆上(使用 malloc)。至少在 64 位系统上,您需要大约 1.6 GB,这应该不是问题。将矩阵存储在堆栈上肯定会导致堆栈溢出。
-
@nwellnhof 我已经尝试过了。它没有用。
-
怎么还不够?分配1.6G内存应该没问题。如果您在 linux 中工作,我认为
brk(2)或sbrk(2)应该允许您提高分配限制。或者,更简单的方法是使用mmap(2)。它允许您分配 looooooots 的内存页面。