Search code examples
c++pointersmemorysegmentation-faultmmap

Using mmap() inside a function


I am trying to use mmap to put a file into memory using an object function. I think I have a problem with my pointers but I can't really get it. When I use mmap in the main() everything goes well:

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);
}

And I get the following (expected) output:

File size is 73004383 bytes
mmap will map 2 pages for a total of 8192 bytes
map:    0x7fb8b0bed000
J

The problem arises whenever I try to use mmap from an object function:

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]);
}

The mmap() does not work and I get a seg fault:

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

Solution

  • In this line

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

    fd is set to 0 or 1 (true or false) because the comparison is evaluated before the assignment. Try

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

    instead