Last active
April 22, 2023 15:52
-
-
Save smarteist/e76e8e16b8299dd14f3432d354bf5543 to your computer and use it in GitHub Desktop.
allocate two pages, in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An example output of this program: