will we get major page faults the FIRST time we write into this buffer, and if so why ?
You might or might not get one normal page fault for the first write.
It depends on which OS (and which implementation of malloc()
); but I'd expect that (for most operating systems and most implementations of malloc()
):
the malloc()
causes virtual pages to be created, where those virtual pages are the same physical page full of zeros mapped many times at many virtual addresses as "read only" (it's a little bit like using mirrors to make it look like a single banana is a room full of bananas).
when you write to one of the pages for the first time, you get one page fault, and the OS allocates a new physical page, fills it with zeros, and maps it at the appropriate address in the virtual address space as "read/write" (replacing the old "read only" page full of zeros).
this probably happens for each individual virtual page (e.g. writing to one virtual page won't cause any other virtual page to become allocated or "read/write"). However, an OS may (if there's lots of spare RAM, and/or if the OS detected an easily predicted "sequential write" pattern), pre-allocate physical pages before you write to them (to avoid future page faults); and an OS may decide to use a different/larger page size (e.g. instead of allocating a 4 KiB page it might allocate a 2 MiB "large page" instead).
for some implementations of malloc()
(and some values of SIZE
), some of the virtual memory may already be allocated and mapped during malloc()
(e.g. because malloc()
wrote a header at the start of the allocated block and caused the page fault itself).
you may get more page faults later (e.g. if you have one page fault on the first write that allocates the page; then data in the allocated page may be sent to swap space to free the physical page later, and then subsequent reads or writes will cause more page faults to fetch the data from swap space).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…