Skip to content

Instantly share code, notes, and snippets.

@smarteist
Last active April 22, 2023 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarteist/e76e8e16b8299dd14f3432d354bf5543 to your computer and use it in GitHub Desktop.
Save smarteist/e76e8e16b8299dd14f3432d354bf5543 to your computer and use it in GitHub Desktop.
allocate two pages, in C
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
// same as calling sbrk(0)
void *get_brk (void)
{
return (void *) syscall (SYS_brk, 0);
}
int main ()
{
void *start_brk, *end_brk, *new_brk;
long page_size = sysconf (_SC_PAGESIZE);
printf ("Page Size: %ld\n", page_size);
// Get the initial starting address of the heap
start_brk = get_brk ();
printf ("Initial heap start: %p\n", start_brk);
// Allocate an entire page using sbrk
new_brk = sbrk (page_size);
end_brk = get_brk ();
printf ("New heap start after allocating one page: %p\n", new_brk);
printf ("New heap end after allocating one page: %p\n", end_brk);
printf ("Address diff: %ld\n", end_brk - start_brk);
// Extend the heap to two pages using brk
new_brk = (void *) ((char *) start_brk + 2 * page_size);
if (brk (new_brk) != 0)
{
perror ("brk");
}
end_brk = get_brk ();
printf ("New heap start after extending to two pages: %p\n", start_brk);
printf ("New heap end after extending to two pages: %p\n", end_brk);
printf ("Address diff: %ld\n", end_brk - start_brk);
return 0;
}
@smarteist
Copy link
Author

An example output of this program:

Page Size: 4096
Initial heap start: 0x5596cc2a6000
New heap start after allocating one page: 0x5596cc2a6000
New heap end after allocating one page: 0x5596cc2a7000
Address diff: 4096
New heap start after extending to two pages: 0x5596cc2a6000
New heap end after extending to two pages: 0x5596cc2a8000
Address diff: 8192

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment