]> jfr.im git - irc/quakenet/newserv.git/blob - core/nsmalloc.c
770384bc2a4f6871330eb08a048f8ca8d92ec7ac
[irc/quakenet/newserv.git] / core / nsmalloc.c
1 /* nsmalloc: Simple pooled malloc() thing. */
2
3 #include <stdlib.h>
4
5 #include "nsmalloc.h"
6 #include "../core/error.h"
7
8 void *nsmalloc(unsigned int poolid, size_t size);
9 void nsfree(unsigned int poolid, void *ptr);
10 void nsfreeall(unsigned int poolid);
11
12 struct nsminfo {
13 struct nsminfo *next;
14 char data[];
15 };
16
17 struct nsminfo *pools[MAXPOOL];
18
19 void *nsmalloc(unsigned int poolid, size_t size) {
20 struct nsminfo *nsmp;
21
22 if (poolid >= MAXPOOL)
23 return NULL;
24
25 /* Allocate enough for the structure and the required data */
26 nsmp=(struct nsminfo *)malloc(sizeof(struct nsminfo)+size);
27
28 if (!nsmp)
29 return NULL;
30
31 nsmp->next=pools[poolid];
32 pools[poolid]=nsmp;
33
34 return (void *)nsmp->data;
35 }
36
37 void nsfree(unsigned int poolid, void *ptr) {
38 struct nsminfo *nsmp, **nsmh;
39
40 if (poolid >= MAXPOOL)
41 return;
42
43 for (nsmh=&(pools[poolid]);*nsmh;nsmh=&((*nsmh)->next)) {
44 if ((void *)&((*nsmh)->data) == ptr) {
45 nsmp=*nsmh;
46 *nsmh = nsmp->next;
47 free(nsmp);
48 return;
49 }
50 }
51
52 Error("core",ERR_WARNING,"Attempt to free unknown pointer %p in pool %d\n",ptr,poolid);
53 }
54
55 void nsfreeall(unsigned int poolid) {
56 struct nsminfo *nsmp, *nnsmp;
57
58 if (poolid >= MAXPOOL)
59 return;
60
61 for (nsmp=pools[poolid];nsmp;nsmp=nnsmp) {
62 nnsmp=nsmp->next;
63 free(nsmp);
64 }
65
66 pools[poolid]=NULL;
67 }
68