1 #include <stdlib.h>
2 #include <stdio.h>
3 
4 static int total = 0;
5 
6 struct st_memblk {
7 	void *mb_base;
8 	size_t mb_size;
9 } memblock[512];
10 
11 static int nmbs = 0;
12 
dmalloc(size_t size)13 void *dmalloc(size_t size)
14 {
15 	if (nmbs > sizeof(memblock)) {
16 		fprintf(stdout, "dmalloc: ++ Cannot allocate more space: not enough free blocks of memory (nmbs=%d)\n", nmbs);
17 		exit(0);
18 	}
19 
20 	void *alloced = malloc(size);
21 
22 	memblock[nmbs].mb_base = alloced;
23 	memblock[nmbs].mb_size = size;
24 	++nmbs;
25 
26 	fprintf(stdout, "dmalloc: ++ allocating %d bytes\n", size);
27 	total += size;
28 	fprintf(stdout, "dmalloc: ++ total memory usage %d bytes\n", total);
29 	return alloced;
30 }
31 
dfree(void * p)32 void dfree(void *p)
33 {
34 	int i = 0;
35 	for (; i < nmbs; i++) {
36 		if (memblock[i].mb_base == p) {
37 			printf("dfree: ++ unlocking 0x%x, %d bytes\n", (unsigned)p,
38 				memblock[i].mb_size);
39 			printf("dfree: ++ still allocated %d bytes\n",
40 				total -= memblock[i].mb_size);
41 			break;
42 		}
43 	}
44 	free(p);
45 }
46