简体   繁体   English

malloc&calloc

[英]malloc & calloc

As per: 按照:

calloc(20, sizeof(int))
malloc(20 * sizeof(int))

Which will allocate memory for the 20 integers. 这将为20个整数分配内存。

Does malloc() & calloc() allocates virtual or physically continuous space? malloc()calloc()分配虚拟或物理连续的空间?

C doesn't say that the machine has both physical and virtual address space. C没有说机器有物理和虚拟地址空间。

All you know is that you get pointers, and that you can index/dereference them in a continuous fashion as defined by the language's operators. 所有你知道的是你得到指针,并且你可以按语言的运算符定义的连续方式索引/取消引用它们。

If doing so requires the hardware to re-map virtual addresses to physical ones, or send e-mail to someone who replies with the content of the addressed location, is implementation-defined. 如果这样做需要硬件将虚拟地址重新映射到物理地址,或者向回复所寻址位置的内容的人发送电子邮件,则是实现定义的。

Whether the space is physically continuous or not depends on the platform you are developing on, the MMU and the OS.... 空间是否物理连续取决于您正在开发的平台,MMU和OS ....

Virtually it will be continuous, always. 实际上它总是连续的。

Whether it is calloc or malloc will not make a difference. 无论是calloc还是malloc都不会有所作为。

Both will allocate contiguous virtual memory. 两者都将分配连续的虚拟内存。 Now assume you are running a system where paging is used as virtual memory management. 现在假设您正在运行一个将分页用作虚拟内存管理的系统。 The ten first words might be allocated at the end of a page frame, and the last ten will be allocated at the beginning of another page frame. 可以在页面框架的末尾分配十个第一个单词,并且在另一个页面框架的开头分配最后十个单词。 Physical page allocation depends on the kernel, not on {m|c}alloc() implementation. 物理页面分配取决于内核,而不是{m|c}alloc()实现。 These will just ask for more memory through a system call (see brk() , mmap() ). 这些只是通过系统调用请求更多内存(参见brk()mmap() )。 Because physical page frame allocation is not necessarily contiguous , you will end up with one part of your allocation falling into one page, and the one falling into another one. 因为物理页面框架分配不一定是连续的,所以最终会将一部分分配落入一个页面,而另一部分落入另一个页面。

In most cases, you just don't have to bother with whether your data will cross a page boundary, unless you are looking for optimizations and you want to avoid excessive minor pagefaults. 在大多数情况下,除了您正在寻找优化并且您希望避免过多的次要页面故障之外,您不必担心数据是否会跨越页面边界。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM