malloc 和 calloc 的区别? [英] Difference between malloc and calloc?

查看:28
本文介绍了malloc 和 calloc 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做和做有什么区别:

ptr = (char **) malloc (MAXELEMS * sizeof(char *));

或:

ptr = (char **) calloc (MAXELEMS, sizeof(char*));

什么时候使用 calloc 而不是 malloc 是一个好主意,反之亦然?

When is it a good idea to use calloc over malloc or vice versa?

推荐答案

calloc() 给你一个零初始化的缓冲区,而 malloc() 使内存未初始化.

calloc() gives you a zero-initialized buffer, while malloc() leaves the memory uninitialized.

对于大量分配,主流操作系统下的大多数 calloc 实现将从操作系统获取已知归零页面(例如通过 POSIX mmap(MAP_ANONYMOUS) 或 Windows VirtualAlloc) 所以它不需要在用户空间中编写它们.这也是正常的 malloc 从操作系统获取更多页面的方式;calloc 只是利用了操作系统的保证.

For large allocations, most calloc implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS) or Windows VirtualAlloc) so it doesn't need to write them in user-space. This is how normal malloc gets more pages from the OS as well; calloc just takes advantage of the OS's guarantee.

这意味着 calloc 内存仍然可以是干净的"和延迟分配的,并且写时复制映射到系统范围的零共享物理页面.(假设系统具有虚拟内存.)

This means calloc memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)

有些编译器甚至可以为您优化 malloc + memset(0) 为 calloc,但如果您希望内存读取为 0,则应明确使用 calloc.

Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0.

如果您在写入之前不打算读取内存,请使用 malloc 以便它可以(可能)从其内部空闲列表中为您提供脏内存,而不是从操作系统获取新页面.(或者代替将空闲列表上的一块内存清零以获得小分配).

If you aren't going to ever read memory before writing it, use malloc so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).

如果没有操作系统,calloc 的嵌入式实现可能会让 calloc 自己将内存归零,或者它不是一个花哨的多用户操作系统,将页面归零以停止进程间信息泄露.

Embedded implementations of calloc may leave it up to calloc itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.

在嵌入式 Linux 上,malloc 可以 mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS),它只对一些嵌入式内核启用,因为它在多用户系统上不安全.

On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS), which is only enabled for some embedded kernels because it's insecure on a multi-user system.

这篇关于malloc 和 calloc 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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