I took on a for-fun task of creating a memory allocator which uses process memory rather than making a bunch of system calls to the operating system. The task was: implement my own malloc()
and free()
functions which are limited to a pool (stack array) of 20000 bytes. I already had my own malloc and free implementations which used the sbrk()
in unistd.h, but I realized the difference here would be that I need to re-create an sbrk that instead of getting memory from the OS, gets memory from my array. I had no experience doing this and was quite frankly pretty unfamiliar with how sbrk()
worked internally. Even more, I still don't fully understand unistd's sbrk()
integer pointer param. Nevertheless, I came up with a way to imitate the functionality below:
#define MEMORY_CAPACITY 20000
//NOTE: These are GLOBAL variables below
char global_mem[MEMORY_CAPACITY] = {0};
void *p_break = &global_mem;
void* mov_sbrk(int increment)
{
void *final_address = (char*) global_mem + (MEMORY_CAPACITY-1);
void *original = p_break;
if(increment == 0)
{
return p_break;
}
if(((char*)p_break + increment) < (char*)global_mem)
{
ERR("mov_sbrk: Cannot move to address prior to start of memory.");
return (void*) -1;
}
if(((char*)p_break + increment) > (char*)final_address)
{
ERR("You've run out of memory!");
return (void*) -1;
}
p_break = (void*) ((char*)p_break + increment);
return original;
}
Note that ERR is just a macro for fprintf(stderr, msg)
. Please critique this implementation and let me know if I am missing anything. I've performed some tests with my allocator and so far, it performs as expected. The difference though is that I used a int because a int ptr like the "official" sbrk()
uses as a parameter didn't make sense to me since it would force increments of the architecture's integer size rather than byte-by-byte.
ERR
, you should just include its definition in your program. Note that it then requires<stdio.h>
, too, to declarefprintf()
. \$\endgroup\$