C Everything
This is a C repository containing a curated set of generic data structures and algorithm.
memory_manager.c
Go to the documentation of this file.
1 
5 #include "common.h"
6 
7 static t_mem_manager memer;
8 
13 void mem_init()
14 {
15  memer.mem_record = NULL;
16  memer.alloc_count = 0;
17  memer.free_count = 0;
18 }
19 
24 void mem_finit(void)
25 {
26  t_mem_record *iter = NULL;
28  if (memer.mem_record != NULL) {
29  for (iter = memer.mem_record ; iter != NULL; iter = iter->next) {
30  printf("cleaning up allocated memory space @{%s:%d} [%lu Byte(s)] - %p\n",
31  iter->file, iter->line, iter->block_size, iter->mem);
32  os_free(iter);
33  }
34  }
35  memer.alloc_count = 0;
36  memer.free_count = 0;
37 
38 }
39 
44 t_gen tag_alloc(size_t nmemb, size_t size, char *file, int line)
45 {
46  //TODO:add resource lock
47  t_mem_record *new_mem = os_alloc(1, sizeof(t_mem_record));
48  if (new_mem == NULL) {
49  printf("Memory allocation for tracker failed\n");
50  }
51  new_mem->nmemb = nmemb;
52  new_mem->block_size = size;
53  new_mem->file = file;
54  new_mem->line = line;
55  new_mem->next = NULL;
56 
57  new_mem->mem = os_alloc(nmemb, size);
58  if (new_mem->mem == NULL) {
59  printf("Memory allocation failed\n");
60  }
61  else {
62  memer.alloc_count++;
63  new_mem->next = memer.mem_record;
64  memer.mem_record = new_mem;
65  }
66 
67 
68  return (new_mem->mem);
69 
70 }
71 
72 
73 
78 void untag_alloc(void *mem_addr, char *file, int line)
79 {
80  t_mem_record * mem_list = NULL, *prev_addr = NULL;
81  if (memer.mem_record == NULL)
82  return;
83 
84  for (mem_list = memer.mem_record; mem_list != NULL; prev_addr = mem_list, mem_list = mem_list->next) {
85  if (mem_addr == mem_list->mem) {
86 
87  if (mem_addr == memer.mem_record->mem) {
88  memer.mem_record = mem_list->next;
89  }
90  else {
91  prev_addr->next = mem_list->next;
92  }
93 
94  if (mem_addr) {
95  os_free(mem_addr);
96  mem_addr = NULL;
97  memer.free_count++;
98  }
99 
100  os_free(mem_list);
101  }
102  }
103 }
104 
105 
111 {
112  printf("allocations = %4d , freed allocations = %4d\n",
113  memer.alloc_count, memer.free_count);
114 }
Top level include containg common headers.
void mem_alloc_report(void)
print report of all the assigned memory
void mem_init()
Initailize memory module
void mem_finit(void)
Close memory module by checking and destroying if any tagged memory
void untag_alloc(void *mem_addr, char *file, int line)
deallocate memory and remove from mem list (untagging)
t_gen tag_alloc(size_t nmemb, size_t size, char *file, int line)
allocate memory and store in mem list (tagging)
#define os_free(mem_addr)
Definition: os.h:23
#define os_alloc(nmemb, size)
Custom malloc if not defined use calloc and free.
Definition: os.h:22
t_mem_record * mem_record
struct memory_record * next
void * t_gen
Base Data type used for all data structure and data elements.
Definition: typedefs.h:41