Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between brk and sbrk

Tags:

c

unix

I new to this can any one tell the exact difference between brk and sbrk with a brief example ? is there any efficiency factor to choose from any of the two? malloc and new internally call brk or sbrk.

like image 239
user3227126 Avatar asked May 21 '16 06:05

user3227126


People also ask

What is the difference between brk () and sbrk ()?

brk identifies the lowest data segment location not used by the caller as addr . This location is rounded up to the next multiple of the system page size. sbrk , the alternate interface, adds incr bytes to the caller data space and returns a pointer to the start of the new data area.

What is brk and sbrk system calls?

brk and sbrk are basic memory management system calls used in Unix and Unix-like operating systems to control the amount of memory allocated to the data segment of the process. These functions are typically called from a higher-level memory management library function such as malloc.

What does sbrk stand for?

brk is short for program break address, whose initial and lowest value is first address after the end of BSS. sbrk stands for space increments after program break address, which means to incrementally add new memory to the heap region, as it is shown below. This system call is actually used by malloc and free .

Is sbrk deprecated?

In fact, sbrk() is pretty much deprecated and right way to get virtual address space is mmap(MAP_ANONYMOUS) or its equivalents.


2 Answers

int brk(void *addr);

brk() sets the end of the data segment to the value specified by addr, when that value is reasonable, the system has enough memory, and the process does not exceed its maximum data size.

On success, brk() returns zero. On error, -1 is returned, and errno is set to ENOMEM.

void *sbrk(intptr_t increment);

sbrk() increments the program's data space by increment bytes. Calling sbrk() with an increment of 0 can be used to find the current location of the program break.

On success, sbrk() returns the previous program break. (If the break was increased, then this value is a pointer to the start of the newly allocated memory). On error, (void *) -1 is returned, and errno is set to ENOMEM.

From linux manual page

like image 67
Patrick Roberts Avatar answered Nov 15 '22 06:11

Patrick Roberts


brk sets the upper limit of the data segment, sbrk increments it. In ancient Unixes malloc/free used sbrk. On modern ones things could be very different, for example, OSX does not use brk/sbrk to manage heap allocations but mmap, brk/sbrk exist but are just emulation in a small segment of memory. This is almost the same on Linux (source code of mention the history of transition from brk/sbrk to mmap).

like image 28
Jean-Baptiste Yunès Avatar answered Nov 15 '22 07:11

Jean-Baptiste Yunès