如何懒惰分配零内存? [英] How to lazy allocate zeroed memory?

查看:232
本文介绍了如何懒惰分配零内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,我必须在callocmalloc之间进行选择,c0将分配零内存,而c1可根据需要分配内存.

From what I understand, I have to choose between calloc, which will allocate zeroed memory, and malloc, which can allocate memory on demand.

是否有一个结合了这两个属性的函数?也许直接拨打mmap?

Is there a function that combines both those properties? Maybe direct call to mmap?

如果可能,为什么calloc不这样做?

If it's possible, why calloc doesn't do it?

推荐答案

有几种机制可以从操作系统获取预先清零的内存:

There are a few mechanisms to get pre-zeroed memory from the operating system:

mmap(2)MAP_ANONYMOUS标志强制将内容初始化为零.

mmap(2)'s MAP_ANONYMOUS flag forces the contents to be initialized to zero.

POSIX共享内存段也可以为零

The POSIX shared memory segments can also zero

  • shm_open(3)为您提供文件描述符
  • ftruncate(2)将文件"设置为所需大小
  • mmap(2)将文件"放入您的地址空间
  • shm_open(3) provides you with a file descriptor
  • ftruncate(2) the "file" to the size you want
  • mmap(2) the "file" into your address space

内存已预先清零:

   This volume of IEEE Std 1003.1-2001 specifies that memory
   objects have initial contents of zero when created. This is
   consistent with current behavior for both files and newly
   allocated memory. For those implementations that use physical
   memory, it would be possible that such implementations could
   simply use available memory and give it to the process
   uninitialized. This, however, is not consistent with standard
   behavior for the uninitialized data area, the stack, and of
   course, files. Finally, it is highly desirable to set the
   allocated memory to zero for security reasons. Thus,
   initializing memory objects to zero is required.

该内存似乎在使用时被清零:mm/shmem.c函数shmem_zero_setup():

It appears that this memory is zeroed at use: mm/shmem.c function shmem_zero_setup():

/**
 * shmem_zero_setup - setup a shared anonymous mapping
 * @vma: the vma to be mmapped is prepared by do_mmap_pgoff
 */     
int shmem_zero_setup(struct vm_area_struct *vma)
{   
    struct file *file;
    loff_t size = vma->vm_end - vma->vm_start;

    file = shmem_file_setup("dev/zero", size, vma->vm_flags);
    if (IS_ERR(file))
        return PTR_ERR(file);

    if (vma->vm_file)
        fput(vma->vm_file);
    vma->vm_file = file;
    vma->vm_ops = &shmem_vm_ops;
    return 0;
}

这篇关于如何懒惰分配零内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆