|
对于下面一个程序,就是把一个文件映射到内存,然后创建一个新文件也映射到内存,然后调用memfrob()函数把源文件的内存块加密,再把加密的内存块复制到新文件那里去。
但是却总是段错误,难道这个函数有什么限制么?
如果不要那个加密的函数的话就能够正常复制。
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <unistd.h>
- #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
- int
- main(int argc, char *argv[])
- {
- int fdin, fdout;
- void *src, *dst;
- struct stat statbuf;
- if(argc != 3)
- {
- printf("usage: %s <fromfile> <tofile>", argv[0]);
- return 0;
- }
- fdin = open(argv[1], O_RDONLY);
- fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
- fstat(fdin, &statbuf);
- lseek(fdout, statbuf.st_size - 1, SEEK_SET);
- write(fdout, "", 1);
- src = mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, fdin, 0);
- dst = mmap(0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0);
- memfrob(src, statbuf.st_size);
- memcpy(dst, src, statbuf.st_size);
-
- return 0;
- }
复制代码
尝试加密一个小文件。
- lucifer@cross:~/tmp$ cat tmp3.c
- /*printf 枚举可显示枚举的序号*/
- #include <stdio.h>
- int main(void)
- {
- enum ABC{AAA,BBB,CCC};
- enum ABC e1,e2,e3;
- e1 = AAA;
- e2 = BBB;
- e3 = CCC;
- printf("%d,%d,%d\n",e1,e2,e3);
- getchar();
- return 0;
- }
- lucifer@cross:~/tmp$ ./a.out tmp3.c ddd
- Segmentation fault
- lucifer@cross:~/tmp$
复制代码
GDB的调试信息,说明了是 memfrob () 函数出问题了。
- lucifer@cross:~/tmp$ gdb -q ./a.out
- Reading symbols from /home/lucifer/tmp/a.out...done.
- (gdb) r tmp3.c ddd
- Starting program: /home/lucifer/tmp/a.out tmp3.c ddd
- Program received signal SIGSEGV, Segmentation fault.
- 0x00007ffff7ae184e in memfrob () from /lib/libc.so.6
- (gdb) q
- A debugging session is active.
- Inferior 1 [process 6216] will be killed.
- Quit anyway? (y or n) y
- lucifer@cross:~/tmp$
复制代码 |
|