malloc.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. /**************************************************************
  4. This file contains the custom memory allocator code. This is
  5. used to allocate small chunks of memory a few bytes in size.
  6. On most systems, the memory page size is expected to be 4KB.
  7. I sincerely hope that allocating memory in blocks that are
  8. multiples of memory pages will help avoid memory fragmentation.
  9. **************************************************************/
  10. //about 16MiB
  11. #define PAGE_SIZE 4096
  12. #define CUSTOM_MALLOC_BUFSIZE ( PAGE_SIZE * 4096 ) - sizeof( void* ) - sizeof( size_t )
  13. struct memory_buf{
  14. char buf[CUSTOM_MALLOC_BUFSIZE];
  15. size_t used;
  16. struct memory_buf* next;
  17. };
  18. //cma means Custom Memory Allocation
  19. static struct memory_buf* g_cma_root;
  20. static struct memory_buf* g_cma_memory;
  21. int customMallocInit( void ){
  22. g_cma_root = malloc( sizeof(struct memory_buf) );
  23. if( !g_cma_root ){
  24. printf( "%s: Memory allocation failed.\n", __FUNCTION__ );
  25. return -1;
  26. }
  27. g_cma_root->next = NULL;
  28. g_cma_memory = g_cma_root;
  29. g_cma_memory->used = 0;
  30. return 0;
  31. }
  32. void* customMalloc( size_t count ){
  33. void* p;
  34. if( count > CUSTOM_MALLOC_BUFSIZE - g_cma_memory->used ){
  35. if( count > CUSTOM_MALLOC_BUFSIZE ) return NULL;
  36. g_cma_memory->next = malloc( sizeof(struct memory_buf) );
  37. if( !g_cma_memory->next ){
  38. printf( "%s: Memory allocation failed.\n", __FUNCTION__ );
  39. return NULL;
  40. }
  41. g_cma_memory = g_cma_memory->next;
  42. g_cma_memory->next = NULL;
  43. g_cma_memory->used = 0;
  44. }
  45. p = g_cma_memory->buf + g_cma_memory->used;
  46. g_cma_memory->used += count;
  47. return p;
  48. }
  49. void customFreeAll( void ){
  50. struct memory_buf* next;
  51. while( g_cma_root ){
  52. next = g_cma_root->next;
  53. free( g_cma_root );
  54. g_cma_root = next;
  55. }
  56. }