Created
March 7, 2017 15:21
-
-
Save jeremysinger/46a2d5d87f15218d4d83f2d889228748 to your computer and use it in GitHub Desktop.
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> | |
#define END_OF_LIST (void *)-1 | |
typedef union FreeListCell { | |
union FreeListCell *next; | |
char str[CELL_SIZE_IN_BYTES]; | |
} cell; | |
// global pointer, for free list management | |
cell *next_free; | |
void init_mem_pool() { | |
int i; | |
cell *curr_ptr; | |
next_free = (cell *)sbrk(sizeof(cell)*NUM_CELLS); | |
if (next_free == END_OF_LIST) { | |
// unable to allocate memory | |
fprintf(stderr, "sbrk failed"); | |
exit(-1); | |
} | |
curr_ptr = next_free; | |
for (i=0; i<NUM_CELLS-1; i++) { | |
// set up the initial free-list links | |
curr_ptr->next = (curr_ptr+1); // point to next cell in list | |
curr_ptr++; | |
} | |
// last one - set END_OF_LIST marker | |
(next_free[NUM_CELLS-1]).next = END_OF_LIST; | |
} | |
void *my_malloc(int num_bytes) { | |
cell *ptr; | |
// out of mem | |
if (next_free == END_OF_LIST) | |
return NULL; | |
// if there is a free cell, then advance in linked list | |
ptr = next_free; | |
next_free = next_free->next; | |
return (void *)ptr; | |
} | |
void my_free(void *ptr) { | |
// prepend just free'd cell onto linked list... | |
((cell *)ptr)->next = next_free; | |
next_free = ptr; | |
return; | |
} | |
void out_of_mem() { | |
fprintf(stderr, "out of memory!\n"); | |
exit(-1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment