Page 2 of 2

Re:malloc etc.

Posted: Mon Feb 28, 2005 11:55 am
by Curufir
In *nix terms sbrk just extends the data area of the program.

What happens is you call sbrk with the amount you wish to extend the data area by. sbrk itself is just a wrapper around the system call brk. brk is a system call that sets the end of the data area to a requested value. It's vitally important that you remember all you're really dealing with here is brk, sbrk is just there to make using brk a bit easier in your code.

So brk is called with a new value for the end of the data area. The OS then maps in/out enough pages to fulfil that request (Obviously checking that memory is available). brk doesn't actually return anything useful (Aside from success/failure).

sbrk returns a pointer to start of the newly allocated space. Since brk doesn't provide this information sbrk must keep track of things internally (This is a trivial matter).

So things run something like this:
  • The program's data area starts at A and ends at B.
  • You call sbrk to extend the data area by X bytes.
  • sbrk calls brk to set the a new end of data area to B+X.
  • brk causes the kernel to make the range A -> B+X valid addresses.
  • sbrk returns a pointer to B.
As should be obvious, this means that any program with a data area that isn't exactly divisible by the size of a page will be wasting space. This fragmentation is an unavoidable consequence of using paging whilst segregating programs.

Re:malloc etc.

Posted: Mon Feb 28, 2005 12:09 pm
by Poseidon
looks easier to me to get the last bugs out of my malloc function..