为什么 mmap 在这里不起作用

发布于 2024-12-21 00:57:18 字数 201 浏览 6 评论 0原文

当我运行以下代码时出现分段错误...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

最好是你 2024-12-28 00:57:18

您指定了不正确的标志和文件描述符。看起来您想要的是匿名(不受文件支持)映射。如果是这种情况,正确的调用是:

x = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

您需要使用 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:

x = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

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.

你对谁都笑 2024-12-28 00:57:18

好的,我明白了。我忘记放置MAP_ANONYMOUS,所以它应该是这样的......

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 
  0, 0 );

它是这样工作的。

OK, I got it. I forgot to place MAP_ANONYMOUS, so it should had been like this...

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 
  0, 0 );

Its working this way.

白首有我共你 2024-12-28 00:57:18

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.

赤濁 2024-12-28 00:57:18

并且您应该始终检查 mmap 的结果不是 MAP_FAILED (即 (void *) -1)并使用 errno 来获取这种情况下的错误代码。

您的 mmap 可能会失败(例如,由于使用 setrlimit,或者因为交换空间已满)。

And you should always check that the result of mmap is not MAP_FAILED (that is, (void *) -1) and use errno 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文