-2

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?

durron597
  • 31,968
  • 17
  • 99
  • 158
yuwenbao
  • 13
  • 1
  • 3
    If you want to ask such a tool-specific question, please at least give information on file, line number and version of the source code. – maxdev Jul 17 '14 at 13:56
  • 2
    Add context to the question, and add a link to the full source file. – DBedrenko Jul 17 '14 at 13:57
  • Obviously whoever wrote that wants to allocate some more space than given by `insize`/`outsize`. To find out why, you have to look at how the allocated space is used in that program. – sth Jul 17 '14 at 14:23

1 Answers1

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.

nobody
  • 19,814
  • 17
  • 56
  • 77