Say I allocate a big memory (40MB) with mmap using /dev/zero as follows.
fd = open("/dev/zero", O_RDWR);
a = mmap (0, 4096e4, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, fd, 0);
What I understand is that the kernel will initialize memories to zero as the pages are brought into the physical memory (I suppose the modern Linux kernels use Demand paging). So for example, when the first page is touched and therefore brought into the physical memory, kernel will initialize all of its 4096 bytes to zero, then when the second page is touched, it does the same and so on.
Is my understanding correct?
Yes, even more the pages are only brought into existence if you touch them for the first time.
BTW, there is the flag MAP_ANONYMOUS
that you can use in this situation, no need to open a file descriptor on /dev/null
.