Does mmap or malloc allocate RAM?

前端 未结 2 1826
有刺的猬
有刺的猬 2020-12-28 21:17

I know this is probably a stupid question but i\'ve been looking for awhile and can\'t find a definitive answer. If I use mmap or malloc (in C, on

2条回答
  •  渐次进展
    2020-12-28 21:55

    Theory and practice differ greatly here. In theory, neither mmap nor malloc allocate actual RAM, but in practice they do.

    mmap will allocate RAM to store a virtual memory area data structure (VMA). If mmap is used with an actual file to be mapped, it will (unless explicitly told differently) further allocate several pages of RAM to prefetch the mapped file's contents.
    Other than that, it only reserves address space, and RAM will be allocated as it is accessed for the first time.

    malloc, similarly, only logically reserves amounts of address space within the virtual address space of your process by telling the operating system either via sbrk or mmap that it wants to manage some (usually much larger than you request) area of address space. It then subdivides this huge area via some more or less complicated algorithm and finally reserves a portion of this address space (properly aligned and rounded) for your use and returns a pointer to it.
    But: malloc also needs to store some additional information somewhere, or it would be impossible for free to do its job at a later time. At the very least free needs to know the size of an allocated block in addition to the start address. Usually, malloc therefore secretly allocates a few extra bytes which are immediately preceding the address that you get -- you don't know about that, it doesn't tell you.

    Now the crux of the matter is that while in theory malloc does not touch the memory that it manages and does not allocate physical RAM, in practice it does. And this does indeed cause page faults and memory pages to be created (i.e. RAM being used).
    You can verify this under Linux by keeping to call malloc and watch the OOP killer blast your process out of existence because the system runs out of physical RAM when in fact there should be plenty left.

提交回复
热议问题