I'm reading cat source code, but I dont understand the following piece of code
insize = MAX (insize, outsize);
inbuf = xmalloc (insize + page_size - 1);
Why is the buffer created with a size of insize + page_size -1
?
I'm reading cat source code, but I dont understand the following piece of code
insize = MAX (insize, outsize);
inbuf = xmalloc (insize + page_size - 1);
Why is the buffer created with a size of insize + page_size -1
?
This is a common idiom used when you need to allocate a buffer that will be aligned on a page boundary (page-aligned buffers are required by various APIs and can also improve memory throughput). There is no portable way to ask malloc
for a page-aligned buffer, so asking for x + PAGE_SIZE-1
bytes guarantees that you will be able to round the resulting pointer up to the next page boundary and still have it point to a block of at least x
bytes.