Memory Allocators:brk() and sbrk()

In the memory management section we saw that there are three libraries function: malloc(), calloc() and realloc() which are responsible for managing memory dynamically.

Key point to consider that above function are memory managers not memory allocators. Memory allocation is done with the help of system calls: brk() and sbrk().

brk():

  • It stands for break which marks the end point that is the point beyond which the program would break.
  • It specifies the maximum space that can be allocated.
  • If the program tries to access a memory beyond this region, there is an abnormal termination of a process that is a bus errors should be generated.
  • Syntax: brk(const void *addr)
  • It places the break point at a given address and return 0 if successful and -1 otherwise.
  • In the above diagram we can see that heap is a continuous space of memory with three bounds:
    • A starting point
    • A maximum limit( can be managed via getrlimit() and setrlimit().
    • An end point called the break which marks the end of the memory which can be accessed for read n write.

sbrk():

  • sbrk() stand for space increment after program break address.
  • It moves the break by the given increment/decrement(in bytes)
  • It is used to change the space allocated for the calling process. The change is made by adding incr bytes to the process’s break value and allocating appropriate amount of space.
  • The amount of allocated space increases when incr is positive and decreases when incr is negative.
  • Depending upon the system implementation, It either returns the previous break address or the new break value.
  • sbrk(0) returns the previous break value and sbrk(incr>0) returns the new break value.
  • sbrk() is thus used to retrieve the beginning of the heap which is the initial position of the break.
  • Syntax: void *sbrk(intptr_t incr);
  • It returns -1 on failure.

Dummy malloc() implementation:

As discussed internally malloc() uses the brk() and sbrk() system call for allocating a memory. But the below piece of code snippet is just a dummy C code for malloc() for giving the idea about internal working.

* An horrible dummy malloc */

 #include <sys/types.h>
 #include <unistd.h>

 void *malloc(size_t size)
 {
   void *p;
   p = sbrk (0);
   /* If sbrk fails , we return NULL */
   if (sbrk(size) == (void*) -1)
      return NULL;
   return p;
 }

Please refer to internal working of malloc() for correct implementation.

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: