brk v.s. sbrk

brk() and sbrk() are the system calls that is used for memory management. They are often used by the memory allocation like malloc and free in the C standard library.[1]

They change the location of the program break, which defines the end of the process's heap start address and end address.

Usage:

#include "unistd.h"
int brk(void *addr);
void *sbrk(intptr_t increment);

How to Get Current .BSS Location

int bssvar;

int main() {
	printf("end of bss section: %p\n", (long)&bssvar + 4);
	// ...
}

Example

#include <stdio.h> // for printf
#include <stdlib.h> // for exit
#include <unistd.h> // for brk and sbrk

int bssvar; // define a uninitialized variable which will be put in .bss segment

int main(void) {
	char *pmem;
	long heap_gap_bss;
	printf("end of bss section: %p\n", (void *)&bssvar + 4);

	pmem = (char *)malloc(32);
	if (pmem == NULL) {
		perror("malloc");
		exit(EXIT_FAILURE);
	}
	printf("pmem: %p\n", pmem);
	heap_gap_bss = (long)pmem - (long)&bssvar - 4;
	printf("1-gap between heap and bss: %lu\n", heap_gap_bss);
	free(pmem);
	sbrk(32); // adjust program break position.
	pmem = (char*)malloc(32);
	if (pmem == NULL) {
		perror("malloc");
		exit(EXIT_FAILURE);
	}
	printf("pmem: %p\n", pmem);
	heap_gap_bss = (long)pmem - (long)&bssvar - 4;
	printf("2-gap between heap and bss:%lu\n", heap_gap_bss);
	free(pmem);
	return 0;
}

This program showed the following output:

end of bss section: 0x5619096ea018
pmem: 0x56190a5552b0
1-gap between heap and bss: 15119000
pmem: 0x56190a5552b0
2-gap between heap and bss:15119000

  1. https://man7.org/linux/man-pages/man2/brk.2.html ↩︎