简体   繁体   中英

malloc & calloc

As per:

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

Which will allocate memory for the 20 integers.

Does malloc() & calloc() allocates virtual or physically continuous space?

C doesn't say that the machine has both physical and virtual address space.

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....

Virtually it will be continuous, always.

Whether it is calloc or malloc will not make a difference.

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. These will just ask for more memory through a system call (see 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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