C++ 在函数中使用mmap()

C++ 在函数中使用mmap(),c++,pointers,memory,segmentation-fault,mmap,C++,Pointers,Memory,Segmentation Fault,Mmap,我正在尝试使用mmap,使用对象函数将文件放入内存。我想我的指针有问题,但我不能真正理解。当我在main()中使用mmap时,一切都很顺利: int main(){ int fd = open("../../../some_file.txt", O_RDONLY, S_IRUSR); struct stat sb; if(fstat(fd,&sb)==-1) { perror("could not get file size"); exit(

我正在尝试使用mmap,使用对象函数将文件放入内存。我想我的指针有问题,但我不能真正理解。当我在main()中使用mmap时,一切都很顺利:

int main(){
   int fd = open("../../../some_file.txt", O_RDONLY, S_IRUSR);
   struct stat sb;
   if(fstat(fd,&sb)==-1) {
       perror("could not get file size");
       exit(1);
   }
   printf("File size is %ld bytes\n", sb.st_size);
   int B = 5000;
   int pages = int(ceil((double)B/PAGESIZE));
   printf("mmap will map %d pages for a total of %d bytes\n", pages, pages*PAGESIZE);

   char * map = (char*)mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd,0);
   printf("map:\t%p\n", map);
   printf("%c\n", map[0]);

   int res = munmap(map, B);
}
我得到以下(预期)输出:

每当我尝试从对象函数使用mmap时,就会出现问题:

int main(){
   string inputFile = "../../../some_file.txt";
   Input* input = new Input();
   input->read_test(inputFile);
}

class Input{
   Input(void){ }
   void read_test(const string &inputFile) {
      if(fd = open(inputFile.c_str(), O_RDWR, S_IRUSR) == -1 ){
         perror("Error while opening the file\n");
         exit(1);
      }
      struct stat sb;
      if(fstat(fd,&sb)==-1) {
         perror("could not get file size");
         exit(1);
      }
      printf("File size is %ld bytes\n", sb.st_size);
      int B = 5;
      int pages = int(ceil((double)B/pagesize));
      printf("mmap will map %d page(s) for a total of %d bytes\n", pages, pages*pagesize);

      char* map = (char*) mmap(NULL, B, PROT_READ, MAP_PRIVATE, fd, 0);
      printf("map:\t%p\n", map);
      printf("%c\n", map[0]);
}
mmap()不工作,我遇到seg故障:

File size is 73004383 bytes
mmap will map 1 page(s) for a total of 4096 bytes
map:    0xffffffffffffffff
./main line 3:  6505 Segmentation fault      (core dumped) ./main
在这一行

if(fd = open(inputFile.c_str(), O_RDWR, S_IRUSR) == -1 )
fd设置为0或1(true或false),因为比较是在赋值之前计算的。试一试

fd = open(inputFile.c_str(), O_RDWR, S_IRUSR);
if(fd == -1 )

相反

这是否回答了您的问题?
fd = open(inputFile.c_str(), O_RDWR, S_IRUSR);
if(fd == -1 )