我是C的新手,现在我正在学习mmap我想从mmaped文件中得到第N个字节,但是当我用Segmentation Fault (core dumped)测试程序时,我得到这个错误gdb这一行有问题,然后我得到

(gdb) print data[sk]
Cannot access memory at address 0xfe5f07d0
(gdb) print data
$1 = 0xfe5f0000 <Address 0xfe5f0000 out of bounds>

我不知道我为什么会犯这个错误这是我的密码
int main( int argc, char * argv[] ){
    int sk;
    int d;
    char *data;
    size_t s;
    if(argc == 3){
        sk = atoi(argv[2]);
        d = da_open(argv[1]);
        s = da_fileSize(d);
        data = (char*)da_mmap(d, s);
        printf("File Size: %d\n", (int) s);
        printf("%d\n", (int) data[sk]); // this line is bad. But why?
        close(d);
    }
    return 0;
}

这里还有我的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>

int da_open(const char *name);
void *da_mmap(int d, size_t size);
size_t da_fileSize();

int da_open(const char *name){
   int dskr;
   dskr = open( name, O_RDWR );
   if( dskr == -1 ){
      perror( name );
      exit(1);
   }
   printf( "dskr1 = %d\n", dskr );
   return dskr;
}

void *da_mmap(int d, size_t size){
     void *a = NULL;
     a = mmap(NULL, size, PROT_WRITE, MAP_SHARED, d, 0);
     if( a == MAP_FAILED ){
          perror( "mmap failed" );
          abort();
     }
     return a;
}

size_t da_fileSize(int d){
    struct stat info;
    if(fstat(d, &info) == -1) {
        perror("fstat failed");
        exit(1);
    }
    return (size_t)info.st_size;
}

int main( int argc, char * argv[] ){
    int sk;
    int d;
    char *data;
    size_t s;
    if(argc == 3){
        sk = atoi(argv[2]);
        d = da_open(argv[1]);
        s = da_fileSize(d);
        data = (char*)da_mmap(d, s);
        printf("File Size: %d\n", (int) s);
        printf("%d\n", (int) data[sk]);
        close(d);
    }
    return 0;
}

最佳答案

我猜您还需要在mmap中获得读取权限:PROT_WRITE | PROT_READ

关于c - 从mmaped文件中获取第N个字节,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30031853/

10-11 19:52