From 238baca31c0b8da7eaf82a0fdf664700e143680c Mon Sep 17 00:00:00 2001 From: Ardavan Oskooi Date: Fri, 31 Dec 2021 18:41:10 -0800 Subject: [PATCH] fix memory leaks in structure and fields load during checkpointing (#1872) * fix memory leaks in structure and fields load during checkpointing * delete the chi1inv and fields array if it exists and reallocate * in unit test, set gaussian source cutoff to 0 due to off-by-1 timestep counter bug * remove cutoff=0 from unit tests * lazily allocate H only if B is not NULL * allocate fields array for H in PML region --- src/fields_dump.cpp | 9 +++++++-- src/structure_dump.cpp | 2 +- tests/dump_load.cpp | 1 - 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/fields_dump.cpp b/src/fields_dump.cpp index 6fce54e2c..9ccc84e01 100644 --- a/src/fields_dump.cpp +++ b/src/fields_dump.cpp @@ -184,12 +184,17 @@ void fields::load_fields_chunk_field(h5file *h5f, bool single_parallel_file, size_t n = num_f[(chunk_i * NUM_FIELD_COMPONENTS + c) * 2 + d]; realnum **f = field_ptr_getter(chunks[i], c, d); if (n == 0) { - delete[] * f; + delete[] *f; *f = NULL; } else { if (n != ntot) meep::abort("grid size mismatch %zd vs %zd in fields::load", n, ntot); - *f = new realnum[ntot]; + // here we need to allocate the fields array for H in the PML region + // because of H = B in fields_chunk::alloc_f whereby H is lazily + // allocated in fields_chunk::update_eh during the first timestep + const direction d_c = component_direction(c); + if (!(*f) || (*f && is_magnetic(component(c)) && chunks[i]->s->sigsize[d_c] > 1)) + *f = new realnum[ntot]; my_ntot += ntot; } } diff --git a/src/structure_dump.cpp b/src/structure_dump.cpp index d0fcb91a5..e12cc88d0 100644 --- a/src/structure_dump.cpp +++ b/src/structure_dump.cpp @@ -604,7 +604,7 @@ void structure::load(const char *filename, bool single_parallel_file) { } else { if (n != ntot) meep::abort("grid size mismatch %zd vs %zd in structure::load", n, ntot); - chunks[i]->chi1inv[c][d] = new realnum[ntot]; + if (!chunks[i]->chi1inv[c][d]) chunks[i]->chi1inv[c][d] = new realnum[ntot]; my_ntot += ntot; } } diff --git a/tests/dump_load.cpp b/tests/dump_load.cpp index 78685a4e9..fef2006fd 100644 --- a/tests/dump_load.cpp +++ b/tests/dump_load.cpp @@ -169,7 +169,6 @@ int test_periodic(double eps(const vec &), int splitting, const char *tmpdir) { double ttot = 17.0; grid_volume gv = vol3d(1.5, 0.5, 1.0, a); - structure s1(gv, eps); structure s(gv, eps, no_pml(), identity(), splitting); std::string filename_prefix =