【问题标题】:mmap Cannot allocate memory -- definitely not out of memorymmap 无法分配内存——绝对不是内存不足
【发布时间】:2014-05-11 13:18:27
【问题描述】:

无论出于何种原因,我都无法在 C 中使用 mmap 打开任何大小的文件。我可能遗漏了一些明显的东西,因此我们将不胜感激您的建议。我搜索了类似的回复,但没有找到任何帮助。这是我的代码——是的,它非常简单。

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, const char * argv[])
{
void * data;
int fd;
struct stat sb;
fd = open("small.txt", O_RDONLY);

data = mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (data == MAP_FAILED) perror("mmap");

return 0;
}

small.txt 是一个非常小的文本文件,大小为 4.0 K。正在运行的特定机器具有大量 RAM (> 500G)。内存不是这里的问题。我意识到这是我正在做的事情,如果您能指出我将不胜感激。

我得到的错误是“mmap:无法分配内存”

【问题讨论】:

  • 您将未初始化的sb.st_size 作为长度参数传递。这很可能是一个巨大的数字。
  • 就是这样。谢谢!

标签: c memory mmap


【解决方案1】:

也许你可以使用这个代码,请看这个链接:http://man7.org/linux/man-pages/man2/mmap.2.html

int fd;
struct stat sb;
fd = open("small.txt", O_RDONLY);

if (fstat(fd, &sb) == -1)           /* To obtain file size */
    handle_error("fstat");

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 2023-04-05
    • 2012-09-21
    • 2015-08-15
    • 2015-02-22
    • 2020-06-25
    • 1970-01-01
    • 2011-01-11
    • 2014-02-18
    相关资源
    最近更新 更多