c - Why the code about mmap gets the segment fault at the (16384+1) byte, not the (4096 + 1) byte? -


os ubuntu. view, page size 4096, should segment fault @ (4096+1)th byte, gets segment fault when (16384 + 1)th byte wrote.

output: ... 16383 segmentation fault

#include <sys/mman.h>   // memory management. #include <sys/stat.h>   // file stat. man 2 stat #include <fcntl.h>      // o_creat #include <unistd.h>  #include <errno.h> #include <stdio.h>  int main(int argc, char* argv[]) {     const int page_size = getpagesize();     printf("page_size: %d\n", page_size);      int shm_fd = open("shm.temp", o_creat | o_rdwr, s_irwxu);     ftruncate(shm_fd, 1);      char* begin = (char *)mmap(null, 1, prot_read | prot_write, map_private | map_noreserve, shm_fd, 0);     perror("mmap");      begin[0] = 'a';     for(int = 1023;/*i < .. */ ; += 1024) {         begin[i] = 'a';         printf("%d %c\n", i, begin[i] );          begin[i+1] = 'a';         printf("%d %c\n", i+1, begin[i] );     }      return 0; } 

updating:

int pid = getpid(); printf("pid: %d\n", pid);  printf("begin: %x\nbegin+4096: %x\nbegin+16384: %x\n",          (unsigned int)(begin),          (unsigned int)(begin + 4096),         (unsigned int)(begin + 16384)         );    begin[4096] = 'a'; sleep(20); begin[16384] = 'a'; sleep(10); 

the output of a.out &:

pid: 3929 begin: b78a5000 begin+4096: b78a6000 begin+16384: b78a9000 

the output of cat /proc/pid/maps.

b78a5000-b78a6000 rw-p 00000000 08:01 285615     /home/.../try/shm.temp b78a6000-b78a9000 rw-p 00000000 00:00 0  bfb04000-bfb19000 rw-p 00000000 00:00 0          [stack] 

thanks basile's point.

now question changed why there b78a6000-b78a9000. trying figure out. more info welcome.

after use cat /proc/pid/maps, find other mmap-ed segment. use strace a.out. know why there b78a6000-b78a9000.

it comes loader & run-time env before main function.

execve("./a.out", ["./a.out"], [/* 38 vars */]) = 0 brk(0)                                  = 0x85d8000 access("/etc/ld.so.nohwcap", f_ok)      = -1 enoent (no such file or directory) mmap2(null, 8192, prot_read|prot_write, map_private|map_anonymous, -1, 0) = 0xb77f8000 ... , it. 

related point:

g++ -static option! 

now think answer of q. comment, basile's point let me think more.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -