core-lightning/common/autodata.c
Rusty Russell 68043c2e8c common: clean up autodata in common_shutdown().
valgrind locally complains about the allocations in autodata leaking:

```
==138200== 16 bytes in 1 blocks are still reachable in loss record 1 of 2
==138200==    at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==138200==    by 0x10D41A: autodata_register_ (autodata.c:20)
==138200==    by 0x10E7B8: register_autotype_type_to_string (type_to_string.h:79)
==138200==    by 0x10F5CA: register_one_type_to_string0 (block.c:259)
==138200==    by 0x19734C: __libc_csu_init (in /home/rusty/devel/cvs/lightning/common/test/run-route-specific)
==138200==    by 0x4A3D03F: (below main) (libc-start.c:264)
==138200== 
==138200== 176 bytes in 1 blocks are still reachable in loss record 2 of 2
==138200==    at 0x483DFAF: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==138200==    by 0x10D472: autodata_register_ (autodata.c:26)
==138200==    by 0x122D37: register_autotype_type_to_string (type_to_string.h:79)
==138200==    by 0x122F1F: register_one_type_to_string0 (node_id.c:50)
==138200==    by 0x19734C: __libc_csu_init (in /home/rusty/devel/cvs/lightning/common/test/run-route-specific)
==138200==    by 0x4A3D03F: (below main) (libc-start.c:264)
==138200== 
make: *** [Makefile:638: unittest/common/test/run-route-specific] Error 7
```
Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
2021-11-17 10:51:48 +10:30

55 lines
973 B
C

#include "config.h"
#include <assert.h>
#include <ccan/strmap/strmap.h>
#include <common/autodata.h>
struct typereg {
size_t num;
const void **ptrs;
};
static STRMAP(struct typereg *) typemap;
void autodata_register_(const char *typename, const void *ptr)
{
struct typereg *t;
assert(ptr);
t = strmap_get(&typemap, typename);
if (!t) {
t = malloc(sizeof(struct typereg));
t->num = 0;
t->ptrs = NULL;
strmap_add(&typemap, typename, t);
}
t->ptrs = realloc(t->ptrs, (t->num + 1) * sizeof(*t->ptrs));
t->ptrs[t->num] = ptr;
t->num++;
}
void *autodata_get_(const char *typename, size_t *nump)
{
struct typereg *t = strmap_get(&typemap, typename);
if (!t) {
*nump = 0;
return NULL;
}
*nump = t->num;
return t->ptrs;
}
static bool free_one(const char *member,
struct typereg *t, void *unused)
{
free(t->ptrs);
free(t);
return true;
}
void autodata_cleanup(void)
{
strmap_iterate(&typemap, free_one, NULL);
strmap_clear(&typemap);
}