Skip to content

Check for overflow and failure in all memory allocations (fix #11) - #108

Open
M-Colley wants to merge 4 commits into
multi-objective:mainfrom
M-Colley:fix/issue-11
Open

M-Colley wants to merge 4 commits into
multi-objective:mainfrom
M-Colley:fix/issue-11

Conversation

@M-Colley

Copy link
Copy Markdown
Contributor

Closes #11

Split out of #103, which now covers only #8.

Changes

  • moocore_malloc() now checks nmemb * size for overflow, using the same test as OpenBSD reallocarray(). This resolves the FIXME in common.h. New moocore_calloc() and moocore_realloc(), with the macros MOOCORE_CALLOC() and MOOCORE_REALLOC(), apply the same checks.
  • A NULL result counts as a failure only when the requested size is non-zero, because malloc(0) may return NULL.
  • All malloc, calloc and realloc calls in c/ and r/src/ now use the wrappers. A script converted 141 calls of the form n * sizeof(T), and I converted 9 by hand (bit_array.h, eaf.c, io.c, dominatedsets.c).
  • Where sizeof came first in the original expression, the product was computed in size_t. The conversion keeps it in size_t with a cast. For example, malloc(sizeof(double) * nsamples * nobj) becomes MOOCORE_MALLOC((size_t) nsamples * nobj, double), so nsamples * nobj is not computed in int.
  • NULL checks that can no longer trigger are removed: read_point(), m_strcat(), x_strndup(), lex_sort_equal_z_and_setup_nodes(), and the asserts after realloc in eaf_realloc() and cvector.h. Some of these leaked the old pointer when realloc failed. The caller of lex_sort_equal_z_and_setup_nodes() ignored its -1 return value.
  • One call is not converted. hv_inex_list() in hv.c returns -1 when malloc fails, fpli_hv() passes it on, and Python hypervolume() raises MemoryError. Converting it would turn that MemoryError into a process exit. I can convert it too if you prefer one rule everywhere.

Behaviour on failure: in R, the wrappers call Rf_error(), so a failed allocation now raises an R error instead of crashing R. In C and Python, they print the error and call exit(EXIT_FAILURE). Before, an unchecked NULL was dereferenced.

Overlap with #103: both PRs change whv_preprocess_rectangles() in c/whv.c and the NEWS files c/NEWS.md and python/doc/source/whatsnew/index.rst, so whichever PR merges second needs a rebase that keeps the rewritten whv_preprocess_rectangles() from #103.

How I verified it

  • New c/test_alloc.c and a make -C c unittest target, which runs in both jobs of C.yml. It checks moocore_mul_overflow() at the boundaries. For example, 2 * (SIZE_MAX/2) does not overflow and 2 * (SIZE_MAX/2 + 1) does. It also checks that the wrappers return usable memory, that realloc keeps the contents, and that MOOCORE_CALLOC zeroes the memory. Then it calls each wrapper with SIZE_MAX/2 + 1 doubles and expects the overflows size_t error. With the overflow check disabled, 4 assertions and all 3 overflow calls fail.
  • make -C c all DEBUG=0 WERROR=1, make -C c all DEBUG=1 WERROR=1 SANITIZERS= and make -C c shlibs DEBUG=0 WERROR=1 build without warnings.
  • I built the executables from main and from this branch. Their outputs are byte-identical for 16 runs of hv, hvapprox, nondominated -f, eaf, igd, epsilon, dominatedsets and ndsort on files from r/inst/extdata (2D, 3D and 8D). These runs cover the converted command-line code (read_point(), x_strndup(), the results block in dominatedsets.c, and eaf_realloc()).
  • Python suite (pytest --doctest-modules tests src/moocore/_moocore.py): 101 passed, 2 xfailed. The extension was built with MSVC.
  • R testthat with NOT_CRAN=true: 0 failures, 0 errors, 0 skipped.

Environment: Windows 11, Python 3.13, R 4.6.1, GCC 14.3 from Rtools 4.5, MSVC from Visual Studio 18. I have not tested on Linux or macOS locally, so CI covers those.

AI assistance was used to prepare and review this patch.

🤖 Generated with Claude Code

@MLopez-Ibanez

Copy link
Copy Markdown
Contributor

See #107 (comment) and #11 (comment)

@MLopez-Ibanez

Copy link
Copy Markdown
Contributor

There shouldn't be unittests within c/.

The code (and possible failures) should be exercised using the extended testsuite (https://github.com/multi-objective/testsuite) or the Python/R wrappers.

…bjective#11)

 * c/common.h (moocore_mul_overflow): New.
   (moocore_malloc): Stop with an error if nmemb * size overflows
   size_t.  Do not report a NULL result of malloc(0) as a failure.
   (moocore_calloc, moocore_realloc): New.
   (MOOCORE_CALLOC, MOOCORE_REALLOC): New.
 * c/*.c, c/*.h, r/src/Rmoocore.c, r/src/Rcommon.h: Replace malloc(),
   calloc() and realloc() by MOOCORE_MALLOC(), MOOCORE_CALLOC() and
   MOOCORE_REALLOC().  Keep products that were computed in size_t in
   size_t.  Remove NULL checks that can no longer trigger.
   hv_inex_list() keeps its malloc() call because it returns -1 on
   failure, which Python reports as MemoryError.
 * c/test_alloc.c: New unit tests of the wrappers.
 * c/Makefile (unittest): New target.
 * .github/workflows/C.yml: Run make unittest.
@M-Colley

M-Colley commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the feedback, @MLopez-Ibanez. I rebased onto main and updated the PR as requested.

  • c/common.h: Replaced moocore_mul_overflow() with ckd_mul() from <stdckdint.h> when available, with fallbacks to __builtin_mul_overflow() and the OpenBSD reallocarray() check. moocore_malloc() and moocore_realloc() pass the computed total_size directly to malloc() and realloc(), and moocore_calloc() checks overflow via ckd_mul() before calling calloc(). Added moocore_malloc_flex() and MOOCORE_MALLOC_FLEX() for flexible-array allocations.
  • c/ and r/src/Rmoocore.c: Added MOOCORE_MALLOC_SIZE() and MOOCORE_REALLOC_SIZE() so multi-column and 2D allocations pass the row count and row byte size separately, such as MOOCORE_MALLOC_SIZE(n, dim * sizeof(*points)). Converted the new unchecked allocations in c/agree_minmax.h, c/archive.h, c/main-archiver.c, c/treap2d_dlnode.h, c/treap2d_fixed_size.c, and ndtree_assert_valid_tree() in c/nd_tree.h. Left the error-returning allocations in hv_inex_list() and UnboundedArchive unchanged so Python raises MemoryError.
  • Tests: Removed c/test_alloc.c, the unittest target in c/Makefile, and the unittest steps in .github/workflows/C.yml. Added test_hypervolume_memory_error and test_empty_rows in python/tests/test_moocore.py.

This branch has not been deployed

No deployments
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.

Wrap all malloc calls in a wrapper that checks for NULL output and overflow input

2 participants