我在完成代码的内存映射部分时,需要对三个大小不同的数据进行分配,使用的是mmap函数,但是我完成这一块的代码后报错Segmentation fault (core dumped)。我自己看了看感觉没有分配错,但是我检查了下似乎到断言Edge部分(也就是最后)是出现了问题,这是为什么?是我分配的方式有问题吗?
int Graph::map_global_graph(const std::string &path) {
int fd=0;
// Format of graph.size:
// |V|:Number of Nodes(4 Bytes), |E|:Number of Relations(4 Bytes)
// Format of graph:
// Prefix of Node's edge List ((|V|+1)* 4 Bytes), Relations (|E|* 4 Bytes), Relation weights(|E|* 4 Bytes)
std::string graph_size(path);
graph_size.append(".size");
//load_global_graph(path);
// Answer:
fd=open(graph_size.c_str(),O_RDONLY);
//std::cout<<fd<<std::endl;
//if we get a error(open fail)
if (fd == -1){
std::cout<< "Failed to open." << std::endl;
return -1;
}
//get v_cnt,e_cnt
read(fd, &v_cnt, sizeof(int));
read(fd, &e_cnt, sizeof(int));
close(fd);
std::cout<<v_cnt<<" "<<e_cnt<<std::endl;
//map the data for vertex, edge, weight
fd=open(path.c_str(),O_RDONLY);
vertex =(int*)mmap(nullptr, (v_cnt+1)*sizeof(int), PROT_READ, MAP_PRIVATE, fd, 0);
edge =(int*)mmap(nullptr, e_cnt*sizeof(int), PROT_READ, MAP_PRIVATE, fd, (v_cnt+1)*sizeof(int));
edge_weights =(int*)mmap(nullptr, e_cnt*sizeof(int), PROT_READ, MAP_PRIVATE, fd, (v_cnt+1+e_cnt)*sizeof(int));
// Answer
for (int i=0;i < v_cnt;i++) {
if(vertex[i]>=vertex[i+1]){
std::cout<<vertex[i]<<" "<<vertex[i+1]<<" " <<i<<std::endl;
}
assert(vertex[i]<vertex[i+1]);
}
assert(vertex[v_cnt]==e_cnt);
std::cout<<vertex[v_cnt]<<" "<<e_cnt<<std::endl;
for (int i=0;i < e_cnt; i++) {
assert(edge[i] < v_cnt);
assert(edge[i] >= 0);
}
return fd;
}