Skip to content

Instantly share code, notes, and snippets.

@oza
Created December 3, 2009 17:28
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 oza/248351 to your computer and use it in GitHub Desktop.
Save oza/248351 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <assert.h>
#define TEST
#define EASY_ALLOC_MAX_SIZE 0x100000
void* alloc(unsigned long size);
void free(void* ptr);
unsigned long get_index(void);
typedef unsigned char byte;
byte memory[EASY_ALLOC_MAX_SIZE];
unsigned long alloc_index = 0;
/**
* void* easy_alloc
* @unsigned long size : byte to allocate.
*/
void* easy_alloc(unsigned long size)
{
unsigned long i;
void* ret;
i = get_index();
ret = memory + i;
if ( size < EASY_ALLOC_MAX_SIZE ) {
alloc_index += size;
} else {
printf("oops!\n");
}
return ret;
}
/**
* void easy_free
* @void* ptr : address to free.
*/
void easy_free(void* ptr)
{
return;
}
unsigned long get_index(void)
{
return alloc_index;
}
#ifdef TEST
int test_alloc_5byte(void)
{
unsigned long before;
void *ptr;
unsigned long size = 6;
before = get_index();
ptr = easy_alloc(size);
assert( ( before + size ) == get_index() );
assert( ( ptr + size ) == ( memory + get_index() ) );
return 0;
}
int test_alloc_15byte(void)
{
unsigned long before;
void *ptr;
unsigned long size = 15;
before = get_index();
ptr = easy_alloc(size);
assert( ( before + size ) == get_index() );
assert( ( ptr + size ) == ( memory + get_index() ) );
return 0;
}
int test_alloc_90000byte(void)
{
unsigned long before;
void *ptr;
unsigned long size = 90000;
before = get_index();
ptr = easy_alloc(size);
assert( ( before + size ) == get_index() );
assert( ( ptr + size ) == ( memory + get_index() ) );
return 0;
}
int print_before_test(void)
{
printf("MAX size %u\n",EASY_ALLOC_MAX_SIZE);
printf("memory %p\n",memory);
}
int print_after_test(void)
{
printf("index %lu\n",get_index());
printf("memory %p\n", (void*)( memory + get_index() ) );
}
int main(int argc,char* argv)
{
// test it!.
print_before_test();
test_alloc_5byte();
test_alloc_15byte();
test_alloc_90000byte();
print_after_test();
return 0;
}
#endif
all:
gcc easy_alloc.c -o easy_alloc
./easy_alloc
clean:
rm -rf easy_alloc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment