brk Function

Set the end of the process’s data space.

Include

None

Prototype

int brk(void *endds);

Argument

endds pointer to the end of the data segment

Return Value

Returns ‘0’ if successful; otherwise, returns ‘-1’.

Remarks

brk() is used to dynamically change the amount of space allocated for the calling process’s data segment. The change is made by resetting the process’s break value and allocating the appropriate amount of space. The break value is the address of the first location beyond the end of the data segment. The amount of allocated space increases as the break value increases.

Newly allocated space is uninitialized.

This helper function is used by the Standard C Library function malloc().

Default Behavior

If the argument endds is zero, the function sets the global variable __curbrk to the address of the start of the heap and returns zero.

If the argument endds is non-zero and has a value less than the address of the end of the heap, the function sets the global variable __curbrk to the value of endds and returns zero.

Otherwise, the global variable __curbrk is unchanged and the function returns -1.

The argument endds must be within the heap range (see data space memory map below).

Since the stack is located immediately above the heap, using brk() or sbrk() has little effect on the size of the dynamic memory pool. The brk() and sbrk() functions are primarily intended for use in run-time environments where the stack grows downward and the heap grows upward.

The linker allocates a block of memory for the heap if the -Wl,--heap=n option is specified, where n is the desired heap size in characters. The starting and ending addresses of the heap are reported in variables: _heap and _eheap, respectively.

For the 16-bit compiler, using the linker’s heap size option is the standard way of controlling heap size, rather than relying on brk() and sbrk().

File

brk.c