Malloc & calloc

In accordance with:

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

What will allocate memory for integers.

Does malloc() and calloc() provide virtual or physically contiguous space?

+4
source share
3 answers

C does not 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 manner, as defined by language operators.

If this requires that the hardware regroup virtual addresses to physical addresses or send an email to someone who responds with the contents of the addressing, it is determined by implementation.

+9
source

Whether the space is physically continuous or not depends on the platform on which you are developing, the MMU and the OS.

In practice, it will be continuous, always.

Whether it is calloc or malloc will not matter.

+5
source

Both will allocate continuous virtual memory. Suppose you are using a system in which swap is used as virtual memory management. The first ten words can be highlighted at the end of the page frame, and the last ten will be highlighted at the beginning of another page frame. The physical distribution of pages depends on the kernel, and not on the implementation of {m|c}alloc() . They will simply ask for more memory through a system call (see brk() , mmap() ). Since the physical distribution of page frames is not necessarily contiguous, you get one part of your distribution that falls on one page and the other on another.

In most cases, you just don’t need to worry about whether your data will intersect with the page border if you are not looking for optimization and you want to avoid excessive minor errors.

0
source

All Articles