c - mmap: map_anonymous 为什么它给 SIGSEGV?

标签 c linux mmap

为什么这段代码会报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。

最佳答案

检查系统调用的返回值!

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.

关于c - mmap: map_anonymous 为什么它给 SIGSEGV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616746/

相关文章:

c - 在 C 文件中读取(并转换)矩阵

android - __attribute__ ((__constructor__)) 在安卓中

c - 如何检查向上和向下按钮是否在 native C 中被单击

ruby-on-rails - 使用 RubyOnRails 实现每天 100 万页面浏览量的网站...Unicorn 还是 Passenger?

pthreads - 我可以在共享的 POSIX 互斥锁被锁定时重新映射它吗?

linux - mmap() 在可执行文件上使用时如何工作?

linux - 带有 mmap(MAP_FIXED) 的程序在 Linux 2.6.18 && glibc 2.5 上崩溃

C#:函数求值顺序(相对于 C)

c++ - 以编程方式禁用多核

c - 了解 SLIST -queue.h