Skip to content

Fix memory leak and segfault from out-of-order NC file closure - #888

Open
bmribler wants to merge 2 commits into
HDFGroup:masterfrom
bmribler:fix_segfault
Open

Fix memory leak and segfault from out-of-order NC file closure#888
bmribler wants to merge 2 commits into
HDFGroup:masterfrom
bmribler:fix_segfault

Conversation

@bmribler

@bmribler bmribler commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

When opened files were closed in different order than when they were created, segfault and memory leaks occurred.

The global variables
static int _curr_opened = 0; /* the number of files currently opened */
static int _ncdf = 0; /* high water mark on open cdf's */
are used to track open files, but they diverge under out-of-order closure: _curr_opened correctly drops to 0, while
_ncdf does not. A prior memory leak fix changed the teardown check from _curr_opened == 0 to _ncdf == 0, so teardown
never fires in this case — leaking the _cdfs allocation and leaving stale handles that skip validation, causing a segfault later.

This PR reverts the previous change to check _curr_opened == 0 and resets _ncdf and _curr_opened to 0 in ncreset_cdflist on teardown, which would have been correct in the previous fix.

The fix has been verified with an out-of-order LIFO file-closure program under Valgrind.

bmribler and others added 2 commits July 31, 2026 23:11
_curr_opened and _ncdf track open files but diverge when files are
closed out of order: _curr_opened correctly reaches 0, while _ncdf
(high-water mark of _cdfs) does not. A prior fix changed the
teardown check from `_curr_opened == 0` to `_ncdf == 0`, which then
never fired in this case, leaking the _cdfs allocation (81,896
bytes) and leaving stale handles that bypassed validation and
caused an out-of-bounds access / segfault on reuse.

- Revert ncclose/ncabort to check `_curr_opened == 0`
- Reset _ncdf and _curr_opened to 0 in ncreset_cdflist on teardown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant