为什么 mmap 在这里不起作用
当我运行以下代码时出现分段错误...
int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, 0, 0 );
x[0] = 42; // <--- Segmentation fault happens due to this
这里出了什么问题?
I get segmentation fault when I run the following piece of code...
int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, 0, 0 );
x[0] = 42; // <--- Segmentation fault happens due to this
What is wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您指定了不正确的标志和文件描述符。看起来您想要的是匿名(不受文件支持)映射。如果是这种情况,正确的调用是:
您需要使用 MAP_ANONYMOUS 标志来告诉 Linux 没有文件。并且您应该传递
-1
作为文件描述符,而不是 0。You've specified the incorrect flags and file descriptor. It looks like what you want is an anonymous (not backed by a file) mapping. If that's the case, the correct call would be:
You need to use the
MAP_ANONYMOUS
flag to tell Linux there is no file. And you should pass-1
for the file descriptor, not 0.好的,我明白了。我忘记放置MAP_ANONYMOUS,所以它应该是这样的......
它是这样工作的。
OK, I got it. I forgot to place MAP_ANONYMOUS, so it should had been like this...
Its working this way.
man mmap
说:成功时,mmap() 返回指向映射区域的指针。出错时,返回值 MAP_FAILED(即 (void *) -1),并适当设置 errno
检查是否
x == MAP_FAILED
。可能情况就是这样。man mmap
says:On success, mmap() returns a pointer to the mapped area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately
Check, whether
x == MAP_FAILED
or not. May be this is the case.并且您应该始终检查
mmap
的结果不是MAP_FAILED
(即(void *) -1
)并使用errno
来获取这种情况下的错误代码。您的
mmap
可能会失败(例如,由于使用 setrlimit,或者因为交换空间已满)。And you should always check that the result of
mmap
is notMAP_FAILED
(that is,(void *) -1
) and useerrno
to get the error code in that case.Your
mmap
could fail (e.g. because of resource limits set with setrlimit, or because the swap space is full).