c - 如何立即调入新分配的虚拟内存

标签 c linux memory memory-management

我在我的 Linux 用户空间应用程序中分配了一些内存。但是,此内存尚未得到物理内存的支持。

为了使页面被映射,我尝试读取该区域中的每个页面,如下所示。但它并不总是对我有用。

这是我的原始代码:

void Function(void)
{
    char *memory;

    memory = malloc(4096 * 10);
}

这样分配的,虚拟内存还没有映射到物理内存。

所以我修改了代码:

void Function(void)
{
    char *memory;
    volatile uint *accessMemory;

    memory = malloc(4096 * 10);
    accessMemory = (volatile uint *)memory;
    for (i = 0; i < 4096 / 10; i++) {
        printf("%X\n", *accessMemory);
        accessMemory = (volatile uint *)((uint)accessMemory + 4096);
    }
}

但是我还是遇到了同样的问题。我做错了什么?

最佳答案

你的代码有一个明显的问题,转换是一个症状。您为 40960 个字符分配空间,但随后尝试访问无符号 409 个无符号整数,每个整数相隔 4096 个。不仅如此,您还会在执行算术运算之前将指针强制转换为 uint - 这很可能是一种缩小转换,而且绝对不安全。

最好将 memory 指针声明为您打算使用它的类型:

    const size_t page_size = 4096; // TODO: get actual value from system
    uint *memory;
    uint *end;
    volatile uint *p;

    memory = malloc(page_size * 10 * sizeof *memory);
    end = memory + page_size * 10;
    for (p = memory;  p < end;  p += 4096/(sizeof *p))
        printf("%X\n", *p);

话虽如此,如果您希望在页面方面工作,那么使用 mmap() 可能会更好;特别是这个选项:

MAP_POPULATE (since Linux 2.5.46)
Populate (prefault) page tables for a mapping. For a file mapping, this causes read-ahead on the file. Later accesses to the mapping will not be blocked by page faults. MAP_POPULATE is supported for private mappings only since Linux 2.6.23.

关于c - 如何立即调入新分配的虚拟内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600114/

相关文章:

c++ - 将有符号整数位复制到无符号整数的有效方法

python - 如何将 "checkinstall"与使用 "setuptools"的 Python 包一起使用

python - Soundcloud API 在服务器端 Python 身份验证上返回 401 错误

c++ - boost managed_mapped_file 使用我的物理内存吗?

c - 程序在 printf 上挂起或跳过 printf

带哨兵的 C I/O 扫描和打印

c - printf() 是否关心语言环境?

linux - 添加额外的磁盘到根分区(centos6+Plesk)

Linux 设备驱动程序 - 内存映射 I/O 示例讨论

android - 是否可以释放 C++ 分配的内存输出