Memory leak in p4est_destroy
jackerschott opened this issue · 2 comments
When you create a forest and allocate the user data of the quads, like this:
#include <p4est_mesh.h>
static void forest_init_fn(p4est_t *forest, p4est_topidx_t tree, p4est_quadrant_t *quad)
{
void *data = malloc(100);
quad->p.user_data = data;
}
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
MPI_Comm comm = MPI_COMM_WORLD;
p4est_connectivity_t *conn = p4est_connectivity_new_disk2d();
p4est_t *forest = p4est_new(comm, conn, 100, forest_init_fn, NULL);
p4est_destroy(forest);
p4est_connectivity_destroy(conn);
return 0;
}
this memory never gets free'd, which one can confirm with (for example) valgrind:
==1733874== 500 bytes in 5 blocks are definitely lost in loss record 8,345 of 8,544
==1733874== at 0x4845899: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==1733874== by 0x10B835: forest_init_fn (main.c:5)
==1733874== by 0x132692: p4est_quadrant_init_data (p4est_algorithms.c:95)
==1733874== by 0x118CF1: p4est_new_ext (p4est.c:421)
==1733874== by 0x11803D: p4est_new (p4est.c:197)
==1733874== by 0x10B8A3: main (main.c:16)
If I see this correctly, however, this memory should, in p4est_destroy
, be added to a mempool in p4est_quadrant_free_data
, which should be free'd afterwards in sc_mempool_destroy
. So you don't want the user to manually free this memory, right? Then the issue seems to be in sc_array_reset
(called by sc_mempool_destroy
), where the pointer mempool->freed
is free'd, but not the corresponding pointers of the array members, which hold the allocated user data.
p4est_new with data size > 0 already gives you allocated space in quad->p.user_data. You should not assign to the data pointer, just use it, knowing that it holds 100 bytes for your purposes.
Ah, i see. Thank you very much.