mmap:map_anonymous为什么会给SIGSEGV?

时间:2011-12-23 13:40:49

标签: c linux mmap

为什么此代码段会产生分段错误?

#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。

2 个答案:

答案 0 :(得分:10)

检查系统调用的返回值!

mmapflags参数必须具有以下两个选项中的一个:

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

答案 1 :(得分:0)

MAP_FAILED (void*)-1可能会mmap EINVAL errno EINVAL We don't like addr, length, or offset (e.g., they are too large, or not aligned on a page boundary). mmap man page of mmap(2)表示

失败
length

{{1}}的第二个参数(在手册页中称为{{1}})不能为10.它应该是页面长度的倍数(至少为4K)。