为什么这段代码会报segmentation fault?
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
int main()
{
void *ptr;
ptr=mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_ANONYMOUS, -1, 0);
strcpy(ptr, "Hello");
}
或者更好的是,我希望:char *ptr=malloc(10);
然后将此参数传递给 mmap。两者都给出 SIGSEGV。
最佳答案
检查系统调用的返回值!
mmap
的flags
参数必须恰好具有以下两个选项之一:
MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes
that map this file, and are carried through to the underlying file. The file
may not actually be updated until msync(2) or munmap() is called.
MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the mapping are not
visible to other processes mapping the same file, and are not carried through
to the underlying file. It is unspecified whether changes made to the file
after the mmap() call are visible in the mapped region.
你没有提供它,所以 mmap
很可能失败(返回 (void*)-1
),errno
设置为EINVAL
.
关于c - mmap: map_anonymous 为什么它给 SIGSEGV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616746/