From a34c8922aa823544beda3de8dacd2e89bd319867 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 15:47:43 +0100 Subject: [PATCH 1/3] Give empty Action and CHB objects no element buffer and no recorder An Action or CHB over an empty array keeps its shared storage, so it stays initialized with size zero, copyable, and an empty Action still accepts a decay change. It no longer requests or frees a zero-size element buffer and no longer posts a recorder propagator. Zdev-Change-Id: Zd4e6b819bd4f6bcd64b83d6fcd1a94d1bdf26ec1dc2e580c53e90ed98a16a1c9 --- changelog.in | 11 ++ gecode/kernel/branch/action.cpp | 3 +- gecode/kernel/branch/action.hpp | 10 +- gecode/kernel/branch/chb.cpp | 3 +- gecode/kernel/branch/chb.hpp | 22 +++- test/branch.cpp | 211 ++++++++++++++++++++++++++++++++ test/int/open-var-list.cpp | 54 ++++++++ 7 files changed, 304 insertions(+), 10 deletions(-) diff --git a/changelog.in b/changelog.in index 5cd72636c9..d9f9fac2c6 100644 --- a/changelog.in +++ b/changelog.in @@ -157,6 +157,17 @@ Rank: minor Post nothing for relax with empty variable arrays. Debug builds aborted with a failed assertion. +[ENTRY] +Module: kernel +What: bug +Rank: minor +[DESCRIPTION] +Action and CHB information over an empty array, including branching with +ACTION or CHB merits on no variables, requests no heap memory for its values +and posts no recorder propagator. It previously requested zero bytes, which +the C library may answer with a null pointer and thus a MemoryExhausted +exception. + [ENTRY] Module: other What: performance diff --git a/gecode/kernel/branch/action.cpp b/gecode/kernel/branch/action.cpp index e5af174930..bfff8a1168 100644 --- a/gecode/kernel/branch/action.cpp +++ b/gecode/kernel/branch/action.cpp @@ -37,7 +37,8 @@ namespace Gecode { Support::Mutex Action::Storage::m; Action::Storage::~Storage(void) { - heap.free(a, n); + if (n > 0) + heap.free(a, n); } const Action Action::def; diff --git a/gecode/kernel/branch/action.hpp b/gecode/kernel/branch/action.hpp index b2c1223c37..e711f83d51 100644 --- a/gecode/kernel/branch/action.hpp +++ b/gecode/kernel/branch/action.hpp @@ -51,7 +51,7 @@ namespace Gecode { int n; /// Inverse decay factor double invd; - /// Action values (more follow) + /// Action values, null when there are none double* a; /// Initialize action values template @@ -95,6 +95,7 @@ namespace Gecode { * \brief Initialize for views \a x and decay factor \a d and action as defined by \a bm * * Count propagation if \a p is true, count failure if \a f is true. + * For empty \a x, store no values and post no recorder. */ template Action(Home home, ViewArray& x, double d, bool p, bool f, @@ -103,6 +104,7 @@ namespace Gecode { * \brief Initialize for views \a x and decay factor \a d and action as defined by \a bm * * Count propagation if \a p is true, count failure if \a f is true. + * For empty \a x, store no values and post no recorder. */ template void init(Home home, ViewArray& x, double d, bool p, bool f, @@ -271,7 +273,7 @@ namespace Gecode { forceinline Action::Storage::Storage(Home home, ViewArray& x, double d, const typename BranchTraits::Merit& bm) - : n(x.size()), invd(1.0 / d), a(heap.alloc(x.size())) { + : n(x.size()), invd(1.0 / d), a((n > 0) ? heap.alloc(n) : nullptr) { if (bm) for (int i = 0; i < n; i++) { typename View::VarType xi(x[i].varimp()); @@ -342,6 +344,8 @@ namespace Gecode { if (!p && !f) return; object(*new Storage(home, x, d, bm)); + if (x.size() == 0) + return; if (p && f) (void)Recorder::post(home, x, *this); else if (p && !f) @@ -357,6 +361,8 @@ namespace Gecode { if (!p && !f) return; object(*new Storage(home, x, d, bm)); + if (x.size() == 0) + return; if (p && f) (void)Recorder::post(home, x, *this); else if (p && !f) diff --git a/gecode/kernel/branch/chb.cpp b/gecode/kernel/branch/chb.cpp index c87098e2be..2d146ffc8a 100644 --- a/gecode/kernel/branch/chb.cpp +++ b/gecode/kernel/branch/chb.cpp @@ -37,7 +37,8 @@ namespace Gecode { Support::Mutex CHB::Storage::m; CHB::Storage::~Storage(void) { - heap.free(chb, n); + if (n > 0) + heap.free(chb, n); } const CHB CHB::def; diff --git a/gecode/kernel/branch/chb.hpp b/gecode/kernel/branch/chb.hpp index 7c625cb101..c406ec731a 100644 --- a/gecode/kernel/branch/chb.hpp +++ b/gecode/kernel/branch/chb.hpp @@ -65,7 +65,7 @@ namespace Gecode { unsigned long long int nf; /// Alpha value double alpha; - /// CHB information + /// CHB information, null when there is none Info* chb; /// Initialize CHB info template @@ -110,10 +110,18 @@ namespace Gecode { /// Assignment operator GECODE_KERNEL_EXPORT CHB& operator=(const CHB& a); - /// Initialize for views \a x and Q-score as defined by \a bm + /** + * \brief Initialize for views \a x and Q-score as defined by \a bm + * + * For empty \a x, store no values and post no recorder. + */ template CHB(Home home, ViewArray& x, const typename BranchTraits::Merit& bm); - /// Initialize for views \a x and Q-score as defined by \a bm + /** + * \brief Initialize for views \a x and Q-score as defined by \a bm + * + * For empty \a x, store no values and post no recorder. + */ template void init(Home home, ViewArray& x, const typename BranchTraits::Merit& bm); /// Default (empty) chb information @@ -255,7 +263,7 @@ namespace Gecode { template forceinline CHB::Storage::Storage(Home home, ViewArray& x, const typename BranchTraits::Merit& bm) - : n(x.size()), nf(0U), alpha(Kernel::Config::chb_alpha_init), chb(heap.alloc(x.size())) { + : n(x.size()), nf(0U), alpha(Kernel::Config::chb_alpha_init), chb((n > 0) ? heap.alloc(n) : nullptr) { if (bm) { for (int i = 0; i < n; i++) { typename View::VarType xi(x[i].varimp()); @@ -337,14 +345,16 @@ namespace Gecode { CHB::CHB(Home home, ViewArray& x, const typename BranchTraits::Merit& bm) { assert(!*this); object(*new Storage(home, x, bm)); - (void)Recorder::post(home, x, *this); + if (x.size() > 0) + (void)Recorder::post(home, x, *this); } template forceinline void CHB::init(Home home, ViewArray& x, const typename BranchTraits::Merit& bm) { assert(!*this); object(*new Storage(home, x, bm)); - (void)Recorder::post(home, x, *this); + if (x.size() > 0) + (void)Recorder::post(home, x, *this); } template diff --git a/test/branch.cpp b/test/branch.cpp index 3872e0a64a..9236baf5a1 100644 --- a/test/branch.cpp +++ b/test/branch.cpp @@ -1406,6 +1406,217 @@ namespace Test { namespace Branch { } #endif + /// Space without variables for tests on empty arrays + class EmptySpace : public Gecode::Space { + public: + /// Initialize space + EmptySpace(void) {} + /// Constructor for cloning \a s + EmptySpace(EmptySpace& s) : Gecode::Space(s) {} + /// Return the number of propagators + unsigned int + propagators(void) { + return Gecode::PropagatorGroup::all.size(*this); + } + /// Copy space during cloning + Gecode::Space* + copy(void) override { + return new EmptySpace(*this); + } + }; + + /// Integer types for testing action and CHB on empty arrays + class IntEmptyTraits { + public: + using VarArgs = Gecode::IntVarArgs; + using Action = Gecode::IntAction; + using CHB = Gecode::IntCHB; + /// Branch on no variables by action \a a, or by a fresh action if null + static void + branch_action(Gecode::Space& home, const Action* a) { + using namespace Gecode; + branch(home, VarArgs(), (a != nullptr) ? INT_VAR_ACTION_MIN(*a) : INT_VAR_ACTION_MIN(0.9), INT_VAL_MIN()); + } + /// Branch on no variables by CHB \a c, or by a fresh CHB if null + static void + branch_chb(Gecode::Space& home, const CHB* c) { + using namespace Gecode; + branch(home, VarArgs(), (c != nullptr) ? INT_VAR_CHB_MIN(*c) : INT_VAR_CHB_MIN(), INT_VAL_MIN()); + } + }; + + /// Boolean types for testing action and CHB on empty arrays + class BoolEmptyTraits { + public: + using VarArgs = Gecode::BoolVarArgs; + using Action = Gecode::BoolAction; + using CHB = Gecode::BoolCHB; + /// Branch on no variables by action \a a, or by a fresh action if null + static void + branch_action(Gecode::Space& home, const Action* a) { + using namespace Gecode; + branch(home, VarArgs(), (a != nullptr) ? BOOL_VAR_ACTION_MIN(*a) : BOOL_VAR_ACTION_MIN(0.9), + BOOL_VAL_MIN()); + } + /// Branch on no variables by CHB \a c, or by a fresh CHB if null + static void + branch_chb(Gecode::Space& home, const CHB* c) { + using namespace Gecode; + branch(home, VarArgs(), (c != nullptr) ? BOOL_VAR_CHB_MIN(*c) : BOOL_VAR_CHB_MIN(), BOOL_VAL_MIN()); + } + }; + +#ifdef GECODE_HAS_SET_VARS + /// Set types for testing action and CHB on empty arrays + class SetEmptyTraits { + public: + using VarArgs = Gecode::SetVarArgs; + using Action = Gecode::SetAction; + using CHB = Gecode::SetCHB; + /// Branch on no variables by action \a a, or by a fresh action if null + static void + branch_action(Gecode::Space& home, const Action* a) { + using namespace Gecode; + branch(home, VarArgs(), (a != nullptr) ? SET_VAR_ACTION_MIN(*a) : SET_VAR_ACTION_MIN(0.9), + SET_VAL_MIN_INC()); + } + /// Branch on no variables by CHB \a c, or by a fresh CHB if null + static void + branch_chb(Gecode::Space& home, const CHB* c) { + using namespace Gecode; + branch(home, VarArgs(), (c != nullptr) ? SET_VAR_CHB_MIN(*c) : SET_VAR_CHB_MIN(), SET_VAL_MIN_INC()); + } + }; +#endif + +#ifdef GECODE_HAS_FLOAT_VARS + /// Float types for testing action and CHB on empty arrays + class FloatEmptyTraits { + public: + using VarArgs = Gecode::FloatVarArgs; + using Action = Gecode::FloatAction; + using CHB = Gecode::FloatCHB; + /// Branch on no variables by action \a a, or by a fresh action if null + static void + branch_action(Gecode::Space& home, const Action* a) { + using namespace Gecode; + branch(home, VarArgs(), (a != nullptr) ? FLOAT_VAR_ACTION_MIN(*a) : FLOAT_VAR_ACTION_MIN(0.9), + FLOAT_VAL_SPLIT_MIN()); + } + /// Branch on no variables by CHB \a c, or by a fresh CHB if null + static void + branch_chb(Gecode::Space& home, const CHB* c) { + using namespace Gecode; + branch(home, VarArgs(), (c != nullptr) ? FLOAT_VAR_CHB_MIN(*c) : FLOAT_VAR_CHB_MIN(), + FLOAT_VAL_SPLIT_MIN()); + } + }; +#endif + + /** + * \brief %Test action and CHB objects and branching on empty arrays + * + * An empty action or CHB object is initialized with size zero, can be + * copied, and posts no recorder. An empty action accepts a decay change. + */ + template + class EmptyStatistics : public Base { + private: + using VarArgs = typename Traits::VarArgs; + using Action = typename Traits::Action; + using CHB = typename Traits::CHB; + /// Test whether \a s is initialized and empty, also when copied + template + static bool + empty_handle(const Statistics& s) { + Statistics copied(s); + Statistics assigned; + assigned = s; + return s && (s.size() == 0) && copied && (copied.size() == 0) && assigned && (assigned.size() == 0); + } + /// Test an empty action, including a decay change + static bool + empty_action(void) { + EmptySpace home; + Action constructed(home, VarArgs(), 0.9); + Action initialized; + initialized.init(home, VarArgs(), 0.9); + if (!empty_handle(constructed) || !empty_handle(initialized) || (home.propagators() != 0)) + return false; + constructed.decay(home, 0.5); + return constructed.decay(home) == 0.5; + } + /// Test an empty CHB + static bool + empty_chb(void) { + EmptySpace home; + CHB constructed(home, VarArgs()); + CHB initialized; + initialized.init(home, VarArgs()); + return empty_handle(constructed) && empty_handle(initialized) && (home.propagators() == 0); + } + /// Test that the branching posted by \a post adds no propagator and has one solution + static bool + empty_branching(void (*post)(EmptySpace& home)) { + EmptySpace* home = new EmptySpace; + post(*home); + if (home->propagators() != 0) { + delete home; + return false; + } + Gecode::DFS engine(home); + delete home; + int solutions = 0; + while (EmptySpace* s = engine.next()) { + solutions++; + delete s; + } + return solutions == 1; + } + /// Branch by a fresh action + static void + branch_fresh_action(EmptySpace& home) { + Traits::branch_action(home, nullptr); + } + /// Branch by an explicit empty action + static void + branch_given_action(EmptySpace& home) { + Action a(home, VarArgs(), 0.9); + Traits::branch_action(home, &a); + } + /// Branch by a fresh CHB + static void + branch_fresh_chb(EmptySpace& home) { + Traits::branch_chb(home, nullptr); + } + /// Branch by an explicit empty CHB + static void + branch_given_chb(EmptySpace& home) { + CHB c(home, VarArgs()); + Traits::branch_chb(home, &c); + } + + public: + /// Create and register test with name prefix \a prefix + EmptyStatistics(const std::string& prefix) : Base(prefix + "::Branch::EmptyStatistics") {} + /// Run test + bool + run(void) override { + return empty_action() && empty_chb() && empty_branching(&branch_fresh_action) && + empty_branching(&branch_given_action) && empty_branching(&branch_fresh_chb) && + empty_branching(&branch_given_chb); + } + }; + + EmptyStatistics int_empty_statistics("Int"); + EmptyStatistics bool_empty_statistics("Bool"); +#ifdef GECODE_HAS_SET_VARS + EmptyStatistics set_empty_statistics("Set"); +#endif +#ifdef GECODE_HAS_FLOAT_VARS + EmptyStatistics float_empty_statistics("Float"); +#endif + }} // namespace Test::Branch // STATISTICS: test-branch diff --git a/test/int/open-var-list.cpp b/test/int/open-var-list.cpp index 8a5a0d78b4..749165dc4f 100644 --- a/test/int/open-var-list.cpp +++ b/test/int/open-var-list.cpp @@ -570,8 +570,62 @@ namespace Test { namespace Int { namespace OpenList { } }; + class EmptyStatisticsSpace : public Gecode::Space { + public: + Gecode::OpenIntVarList ints; + Gecode::OpenBoolVarList bools; + + EmptyStatisticsSpace(void) : ints(*this, Gecode::IntSet(0, 1), 0), bools(*this, 0) {} + + EmptyStatisticsSpace(EmptyStatisticsSpace& s) : Gecode::Space(s) { + ints.update(*this, s.ints); + bools.update(*this, s.bools); + } + + unsigned int + propagators(void) { + return Gecode::PropagatorGroup::all.size(*this); + } + + Gecode::Space* + copy(void) override { + return new EmptyStatisticsSpace(*this); + } + }; + + class EmptyStatistics : public ::Test::Base { + public: + EmptyStatistics(void) : ::Test::Base("Int::OpenList::EmptyStatistics") {} + + bool + run(void) override { + using namespace Gecode; + for (bool chb : {false, true}) { + EmptyStatisticsSpace* root = new EmptyStatisticsSpace; + unsigned int propagators = root->propagators(); + branch(*root, root->ints, chb ? INT_VAR_CHB_MIN() : INT_VAR_ACTION_MIN(1.0), INT_VAL_MIN()); + branch(*root, root->bools, chb ? BOOL_VAR_CHB_MIN() : BOOL_VAR_ACTION_MIN(1.0), BOOL_VAL_MIN()); + if (root->propagators() != propagators) { + delete root; + return false; + } + DFS engine(root); + delete root; + int solutions = 0; + while (EmptyStatisticsSpace* solution = engine.next()) { + solutions++; + delete solution; + } + if (solutions != 1) + return false; + } + return true; + } + }; + Factory factory; FixedStatistics fixed_statistics; + EmptyStatistics empty_statistics; Selectors selectors; NoGoods no_goods; SelectorChoice selector_choice; From d1b75bb7c87eaf7e246fa79c872c0ac7b0d077a1 Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 18:12:08 +0100 Subject: [PATCH 2/3] Fix the remaining zero-size heap requests and null-pointer library calls TupleSet, Archive, Space::rrealloc, the FlatZinc set and regular builtins, the example dictionary, DFA and TupleSet construction from a DFA, and IntSet initializer lists no longer request zero bytes from the heap or a region and no longer pass null pointers to memcpy. Buffers that can now be null are freed only when non-null. An empty initializer list gives the empty IntSet, and a FlatZinc regular constraint with a reversed final-state range treats it as empty. Zdev-Change-Id: Z739fba34334ff1732238cd5ef32e1903b009ce0fe1dcc1ec967ee3213b53009f --- changelog.in | 39 +++++++++++++++++ cmake/GecodeSources.cmake | 1 + examples/scowl.hpp | 7 ++- gecode/flatzinc/flatzinc.cpp | 19 ++------ gecode/flatzinc/registry.cpp | 11 ++--- gecode/int/extensional/dfa.cpp | 2 +- gecode/int/extensional/tuple-set.cpp | 49 +++++++++++++-------- gecode/int/extensional/tuple-set.hpp | 7 +-- gecode/int/int-set.cpp | 6 ++- gecode/kernel/archive.cpp | 20 ++++++--- gecode/kernel/core.hpp | 6 ++- test/flatzinc/empty_set_literal.cpp | 55 +++++++++++++++++++++++ test/flatzinc/native-registry.cpp | 3 ++ test/int/dom.cpp | 35 +++++++++++++++ test/int/extensional.cpp | 22 +++++++--- test/region.cpp | 65 ++++++++++++++++++++++++++++ 16 files changed, 285 insertions(+), 62 deletions(-) create mode 100644 test/flatzinc/empty_set_literal.cpp diff --git a/changelog.in b/changelog.in index d9f9fac2c6..40a8f6d691 100644 --- a/changelog.in +++ b/changelog.in @@ -168,6 +168,45 @@ and posts no recorder propagator. It previously requested zero bytes, which the C library may answer with a null pointer and thus a MemoryExhausted exception. +[ENTRY] +Module: kernel +What: bug +Rank: minor +[DESCRIPTION] +Copying or assigning an empty Archive requests no heap memory, and growing +space memory with Space::realloc from an empty block copies nothing. They +previously requested zero bytes or passed a null pointer to memcpy. + +[ENTRY] +Module: int +What: bug +Rank: minor +[DESCRIPTION] +Tuple sets of arity zero request no heap memory for tuples and values, also +when they grow or are finalized with a dense representation. They previously +requested zero bytes, which the C library may answer with a null pointer and +thus a MemoryExhausted exception. An IntSet built from an empty initializer +list is the empty set; Debug builds aborted with a failed assertion. + +[ENTRY] +Module: flatzinc +What: bug +Rank: minor +[DESCRIPTION] +Integer and set variables declared with an empty set literal, such as var {} +or var set of {}, request no heap memory. The final states of a regular +constraint given as an interval with a maximum below its minimum are treated +as empty; such an interval previously requested zero bytes or a huge size and +could write before the allocated block. + +[ENTRY] +Module: example +What: bug +Rank: minor +[DESCRIPTION] +A dictionary file holding no accepted word and no final newline requests no +heap memory in the crossword and word-square examples. + [ENTRY] Module: other What: performance diff --git a/cmake/GecodeSources.cmake b/cmake/GecodeSources.cmake index a8deaeca33..3110260d42 100644 --- a/cmake/GecodeSources.cmake +++ b/cmake/GecodeSources.cmake @@ -332,6 +332,7 @@ set(GECODE_TEST_SOURCES test/flatzinc/cutstock.cpp test/flatzinc/empty_domain_1.cpp test/flatzinc/empty_domain_2.cpp + test/flatzinc/empty_set_literal.cpp test/flatzinc/eq20.cpp test/flatzinc/factory_planning_instance.cpp test/flatzinc/golomb.cpp diff --git a/examples/scowl.hpp b/examples/scowl.hpp index 209dfee3a7..00d631d6e2 100644 --- a/examples/scowl.hpp +++ b/examples/scowl.hpp @@ -7820,7 +7820,9 @@ Dictionary::init(const char* fn) { f.close(); } - chunk = static_cast(Gecode::heap.ralloc(sz)); + // A file with no accepted word and no final newline needs no bytes + if (sz > 0) + chunk = static_cast(Gecode::heap.ralloc(sz)); { // Initialize start information in chunk @@ -7900,7 +7902,8 @@ operator<<(std::basic_ostream& os, const Dictionary& d) { } inline Dictionary::~Dictionary(void) { - Gecode::heap.rfree(chunk); + if (chunk != nullptr) + Gecode::heap.rfree(chunk); } // STATISTICS: example-ignore diff --git a/gecode/flatzinc/flatzinc.cpp b/gecode/flatzinc/flatzinc.cpp index 86143e6ef5..8df5d5a098 100644 --- a/gecode/flatzinc/flatzinc.cpp +++ b/gecode/flatzinc/flatzinc.cpp @@ -365,12 +365,7 @@ namespace Gecode { namespace FlatZinc { if (sl->interval) { return IntSet(sl->min, sl->max); } else { - int* newdom = heap.alloc(static_cast(sl->s.size())); - for (int i = sl->s.size(); i--;) - newdom[i] = sl->s[i]; - IntSet ret(newdom, sl->s.size()); - heap.free(newdom, static_cast(sl->s.size())); - return ret; + return IntSet(sl->s.data(), static_cast(sl->s.size())); } } return IntSet(Int::Limits::min, Int::Limits::max); @@ -970,11 +965,7 @@ namespace Gecode { namespace FlatZinc { IntSet d(vsv->min, vsv->max); sv[set_var_count++] = SetVar(*this, d, d); } else { - int* is = heap.alloc(static_cast(vsv->s.size())); - for (int i = vsv->s.size(); i--;) - is[i] = vsv->s[i]; - IntSet d(is, vsv->s.size()); - heap.free(is, static_cast(vsv->s.size())); + IntSet d(vsv->s.data(), static_cast(vsv->s.size())); sv[set_var_count++] = SetVar(*this, d, d); } } else if (vs->upper_bound()) { @@ -983,11 +974,7 @@ namespace Gecode { namespace FlatZinc { IntSet d(vsv->min, vsv->max); sv[set_var_count++] = SetVar(*this, IntSet::empty, d); } else { - int* is = heap.alloc(static_cast(vsv->s.size())); - for (int i = vsv->s.size(); i--;) - is[i] = vsv->s[i]; - IntSet d(is, vsv->s.size()); - heap.free(is, static_cast(vsv->s.size())); + IntSet d(vsv->s.data(), static_cast(vsv->s.size())); sv[set_var_count++] = SetVar(*this, IntSet::empty, d); } } else { diff --git a/gecode/flatzinc/registry.cpp b/gecode/flatzinc/registry.cpp index 252b5e02b6..c565ca20f2 100644 --- a/gecode/flatzinc/registry.cpp +++ b/gecode/flatzinc/registry.cpp @@ -1270,10 +1270,11 @@ namespace Gecode { namespace FlatZinc { // Final states int* f; if (finals->interval) { - f = static_cast(heap.ralloc(sizeof(int) * (finals->max - finals->min + 2))); - for (int i = finals->min; i <= finals->max; i++) - f[i - finals->min] = i; - f[finals->max - finals->min + 1] = -1; + const int n_finals = (finals->min <= finals->max) ? finals->max - finals->min + 1 : 0; + f = static_cast(heap.ralloc(sizeof(int) * (n_finals + 1))); + for (int i = 0; i < n_finals; i++) + f[i] = finals->min + i; + f[n_finals] = -1; } else { f = static_cast(heap.ralloc(sizeof(int) * (finals->s.size() + 1))); for (int j = finals->s.size(); j--;) @@ -1282,7 +1283,7 @@ namespace Gecode { namespace FlatZinc { } DFA dfa(q0, t, f); - free(f); + heap.rfree(f); unshare(s, iv); extensional(s, iv, s.get_shared_dfa(dfa), s.annotation_to_int_prop_level(ann)); } diff --git a/gecode/int/extensional/dfa.cpp b/gecode/int/extensional/dfa.cpp index d88d722f28..dd725139b6 100644 --- a/gecode/int/extensional/dfa.cpp +++ b/gecode/int/extensional/dfa.cpp @@ -195,7 +195,7 @@ namespace Gecode { } // Temporary structure for transitions - Transition* trans = region.alloc(n_trans); + Transition* trans = (n_trans > 0) ? region.alloc(n_trans) : nullptr; if (compact) { for (int i = 0; i < n_trans; i++) { trans[i] = t_spec[i]; diff --git a/gecode/int/extensional/tuple-set.cpp b/gecode/int/extensional/tuple-set.cpp index 62e10cdc96..0ef615de98 100644 --- a/gecode/int/extensional/tuple-set.cpp +++ b/gecode/int/extensional/tuple-set.cpp @@ -96,20 +96,31 @@ namespace Gecode { namespace Int { namespace Extensional { namespace Gecode { + namespace { + + /// Free the heap buffer \a p unless it was never allocated + void + free_buffer(void* p) { + if (p != nullptr) + heap.rfree(p); + } + + } // namespace + /* * Tuple set data * */ void TupleSet::Data::clear_support(void) { - heap.rfree(range); - heap.rfree(range_base); - heap.rfree(support); - heap.rfree(sparse_offsets); - heap.rfree(sparse_tuples); - heap.rfree(sparse_tv); - heap.rfree(compressed_offsets); - heap.rfree(compressed_words); + free_buffer(range); + free_buffer(range_base); + free_buffer(support); + free_buffer(sparse_offsets); + free_buffer(sparse_tuples); + free_buffer(sparse_tv); + free_buffer(compressed_offsets); + free_buffer(compressed_words); range = nullptr; range_base = nullptr; support = nullptr; @@ -215,7 +226,7 @@ namespace Gecode { // Initialization if (n_tuples == 0) { const State selected = empty_state(epk); - heap.rfree(td); + free_buffer(td); td = nullptr; guard.commit(selected); return; @@ -256,7 +267,7 @@ namespace Gecode { for (int a = 0; a < arity; a++) if (!Int::Limits::valid(tuples[t][a])) throw Int::OutOfLimits("TupleSet::finalize()"); - int* new_td = heap.alloc(n_tcells); + int* new_td = (n_tcells > 0UL) ? heap.alloc(n_tcells) : nullptr; for (int t = 0; t < n_tuples; t++) { for (int a = 0; a < arity; a++) { new_td[static_cast(t) * static_cast(arity) + @@ -265,7 +276,7 @@ namespace Gecode { } tuples[t] = new_td + static_cast(t) * static_cast(arity); } - heap.rfree(td); + free_buffer(td); td = new_td; } @@ -349,7 +360,7 @@ namespace Gecode { * Pass 2: allocate memory and fill data structures */ // Allocate memory for ranges - Range* range_cursor = range = heap.alloc(n_ranges); + Range* range_cursor = range = (n_ranges > 0U) ? heap.alloc(n_ranges) : nullptr; // Allocate and initialize memory for support data. support = nullptr; sparse_n_vals = 0U; @@ -364,7 +375,8 @@ namespace Gecode { if (build_dense) { assert((n_words == 0U) || (n_vals <= std::numeric_limits::max() / n_words)); n_support_entries_u32 = n_words * n_vals; - support_cursor = support = heap.alloc(n_support_entries_u32); + support_cursor = support = + (n_support_entries_u32 > 0U) ? heap.alloc(n_support_entries_u32) : nullptr; for (unsigned int i = 0; i < n_support_entries_u32; i++) support_cursor[i].init(); } @@ -552,14 +564,15 @@ namespace Gecode { TupleSet::Data::resize(void) { assert(n_free == 0); int n = static_cast(1 + n_tuples * 1.5); - td = heap.realloc(td, n_tuples * arity, n * arity); + if (arity > 0) + td = heap.realloc(td, n_tuples * arity, n * arity); n_free = n - n_tuples; } TupleSet::Data::~Data(void) { clear_support(); - heap.rfree(td); - heap.rfree(vd); + free_buffer(td); + free_buffer(vd); } /* @@ -633,8 +646,8 @@ namespace Gecode { assert(layers[0].states[0].tuples != nullptr); // Allocate temporary memory for edges and supports - Edge* edges = r.alloc(dfa.max_degree()); - Support* supports = r.alloc(dfa.n_symbols()); + Edge* edges = (dfa.max_degree() > 0U) ? r.alloc(dfa.max_degree()) : nullptr; + Support* supports = (dfa.n_symbols() > 0U) ? r.alloc(dfa.n_symbols()) : nullptr; // Forward pass: accumulate for (int i = 0; i < a; i++) { diff --git a/gecode/int/extensional/tuple-set.hpp b/gecode/int/extensional/tuple-set.hpp index 02116d986f..feb5fa91be 100644 --- a/gecode/int/extensional/tuple-set.hpp +++ b/gecode/int/extensional/tuple-set.hpp @@ -62,9 +62,10 @@ namespace Gecode { TupleSet::Data::Data(int a) : arity(a), n_words(0U), // To be initialized in finalize n_tuples(0), n_free(n_initial_free), min(Int::Limits::max), max(Int::Limits::min), key(0), - td(heap.alloc(n_initial_free * a)), vd(heap.alloc(a)), range(nullptr), range_base(nullptr), - support(nullptr), state(TS_BUILDING), sparse_n_vals(0U), sparse_offsets(nullptr), sparse_tuples(nullptr), - sparse_tv(nullptr), compressed_offsets(nullptr), compressed_words(nullptr), compressed_n_entries(0U) {} + td((a > 0) ? heap.alloc(n_initial_free * a) : nullptr), vd((a > 0) ? heap.alloc(a) : nullptr), + range(nullptr), range_base(nullptr), support(nullptr), state(TS_BUILDING), sparse_n_vals(0U), + sparse_offsets(nullptr), sparse_tuples(nullptr), sparse_tv(nullptr), compressed_offsets(nullptr), + compressed_words(nullptr), compressed_n_entries(0U) {} forceinline bool TupleSet::Data::finalized(void) const { diff --git a/gecode/int/int-set.cpp b/gecode/int/int-set.cpp index f3007288b2..a5761ac38d 100644 --- a/gecode/int/int-set.cpp +++ b/gecode/int/int-set.cpp @@ -199,7 +199,8 @@ namespace Gecode { IntSet::IntSet(std::initializer_list r) { int n = static_cast(r.size()); - assert(n > 0); + if (n == 0) + return; Region reg; Range* dr = reg.alloc(n); int j = 0; @@ -212,7 +213,8 @@ namespace Gecode { IntSet::IntSet(std::initializer_list> r) { int n = static_cast(r.size()); - assert(n > 0); + if (n == 0) + return; Region reg; Range* dr = reg.alloc(n); int j = 0; diff --git a/gecode/kernel/archive.cpp b/gecode/kernel/archive.cpp index 8eaf9db2f0..3d048b0bd8 100644 --- a/gecode/kernel/archive.cpp +++ b/gecode/kernel/archive.cpp @@ -41,23 +41,31 @@ namespace Gecode { _size = m; } - Archive::Archive(const Archive& e) : _size(e._n), _n(e._n), _pos(e._pos) { - _a = heap.alloc(_n); - heap.copy(_a, e._a, _n); + Archive::Archive(const Archive& e) : _size(e._n), _n(e._n), _a(nullptr), _pos(e._pos) { + if (_n > 0) { + _a = heap.alloc(_n); + heap.copy(_a, e._a, _n); + } } Archive& Archive::operator=(const Archive& e) { if (this != &e) { - _a = heap.realloc(_a, _size, e._n); - heap.copy(_a, e._a, e._n); + if (e._n > 0) { + _a = heap.realloc(_a, _size, e._n); + heap.copy(_a, e._a, e._n); + } else if (_a != nullptr) { + heap.free(_a, _size); + _a = nullptr; + } _size = _n = e._n; } return *this; } Archive::~Archive(void) { - heap.free(_a, _size); + if (_a != nullptr) + heap.free(_a, _size); } } // namespace Gecode diff --git a/gecode/kernel/core.hpp b/gecode/kernel/core.hpp index 7b075bb0e2..08d0565159 100644 --- a/gecode/kernel/core.hpp +++ b/gecode/kernel/core.hpp @@ -3272,8 +3272,10 @@ namespace Gecode { char* b = static_cast(_b); if (n < m) { char* p = static_cast(ralloc(m)); - memcpy(p, b, n); - rfree(b, n); + if (n > 0) { + memcpy(p, b, n); + rfree(b, n); + } return p; } else { rfree(b + m, m - n); diff --git a/test/flatzinc/empty_set_literal.cpp b/test/flatzinc/empty_set_literal.cpp new file mode 100644 index 0000000000..ed7d478ce1 --- /dev/null +++ b/test/flatzinc/empty_set_literal.cpp @@ -0,0 +1,55 @@ +/* + * Main authors: + * Mikael Zayenz Lagerkvist + * + * Copyright: + * Mikael Zayenz Lagerkvist, 2026 + * + * This file is part of Gecode, the generic constraint + * development environment: + * http://www.gecode.dev + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "test/flatzinc.hh" + +namespace Test { namespace FlatZinc { namespace { + /// Helper class to create and register tests + class Create { + public: + /// Perform creation and registration + Create(void) { + (void)new FlatZincTest("empty_set_literal_int_var", "var {}: x :: output_var; solve satisfy;", + "=====UNSATISFIABLE=====\n"); +#ifdef GECODE_HAS_SET_VARS + (void)new FlatZincTest("empty_set_literal_set_var_assigned", + "var set of 1..3: s :: output_var = {}; solve satisfy;", "s = {};\n----------\n"); + (void)new FlatZincTest("empty_set_literal_set_var_upper_bound", + "var set of {}: s :: output_var; solve satisfy;", "s = {};\n----------\n"); +#endif + } + }; + + Create c; +}}} // namespace Test::FlatZinc + +// STATISTICS: test-flatzinc diff --git a/test/flatzinc/native-registry.cpp b/test/flatzinc/native-registry.cpp index aa036a5556..616bc210b0 100644 --- a/test/flatzinc/native-registry.cpp +++ b/test/flatzinc/native-registry.cpp @@ -177,6 +177,9 @@ namespace Test { namespace FlatZinc { namespace { "NativeRegistry::NondeterministicPrefix", "constraint gecode_regular_nfa_int_fzn([0,1],3,0,2,[{1,2},{},{},{3},{},{}],1,{3}); solve satisfy;", sat); + (void)new FlatZincTest("NativeRegistry::RegularReversedFinals", + "var 1..1: x; constraint gecode_regular([x], 1, 1, [1], 1, 3..1); solve satisfy;", + unsat); (void)new FlatZincErrorTest("NativeRegistry::SortSize", "constraint gecode_sort_permutation([1,2],[1],[1,2],1); solve satisfy;", {}, "sort arrays must have equal lengths"); diff --git a/test/int/dom.cpp b/test/int/dom.cpp index 21ae192408..8f942e5efa 100644 --- a/test/int/dom.cpp +++ b/test/int/dom.cpp @@ -156,6 +156,39 @@ namespace Test { namespace Int { } }; + /// %Test for domain constraint (set from an empty initializer list) + class DomDomEmpty : public Test { + /// Whether the list holds ranges rather than values + bool ranges; + /// Return the empty set built from an empty list + Gecode::IntSet + empty_set(void) const { + if (ranges) + return Gecode::IntSet(std::initializer_list>{}); + return Gecode::IntSet(std::initializer_list{}); + } + + public: + /// Create and register test + DomDomEmpty(bool r) + : Test(std::string("Dom::Dom::Empty::") + (r ? "Ranges" : "Values"), 1, -4, 4, true), ranges(r) {} + /// %Test whether \a x is solution + bool + solution(const Assignment&) const override { + return false; + } + /// Post constraint on \a x + void + post(Gecode::Space& home, Gecode::IntVarArray& x) override { + Gecode::dom(home, x[0], empty_set()); + } + /// Post reified constraint on \a x for \a r + void + post(Gecode::Space& home, Gecode::IntVarArray& x, Gecode::Reify r) override { + Gecode::dom(home, x[0], empty_set(), r); + } + }; + const int r[4][2] = {{-4, -3}, {-1, -1}, {1, 1}, {3, 5}}; Gecode::IntSet d(r, 4); @@ -212,6 +245,8 @@ namespace Test { namespace Int { DomDom dd1(1); DomDom dd3(3); DomRangeEmpty dre; + DomDomEmpty dde_values(false); + DomDomEmpty dde_ranges(true); //@} } // namespace Dom diff --git a/test/int/extensional.cpp b/test/int/extensional.cpp index 6ac74bfe59..8c23cd73e0 100644 --- a/test/int/extensional.cpp +++ b/test/int/extensional.cpp @@ -1309,16 +1309,20 @@ namespace Test { namespace Int { }; /// The assignment harness needs one variable even for a nullary table. - class SparseTupleSetNullary : public Test { + class TupleSetNullary : public Test { bool nonempty; Gecode::TupleSet t; public: - SparseTupleSetNullary(bool n) - : Test("Extensional::TupleSet::Sparse::Nullary::" + str(n), 1, 0, 0), nonempty(n), t(0) { + TupleSetNullary(Gecode::ExtensionalPropKind epk, bool n) + : Test("Extensional::TupleSet::" + extensional_kind_name(epk) + "::Nullary::" + str(n), 1, 0, 0), + nonempty(n), t(0) { + // More copies of the empty tuple than the initial capacity of + // 1024 tuples, so that the tuple storage grows if (nonempty) - t.add(Gecode::IntArgs(0)); - t.finalize(Gecode::EPK_SPARSE); + for (int i = 0; i < 1025; i++) + t.add(Gecode::IntArgs(0)); + t.finalize(epk); } bool solution(const Assignment&) const override { @@ -2427,8 +2431,12 @@ namespace Test { namespace Int { SparseTupleSet sparse_tuple_set_unary("Unary", 1, 2000); SparseTupleSet sparse_tuple_set_ternary("Ternary", 3, 1500); SparseTupleSet sparse_tuple_set_high_arity("HighArity", 6, 1000); - SparseTupleSetNullary sparse_tuple_set_nullary(true); - SparseTupleSetNullary sparse_tuple_set_empty(false); + TupleSetNullary sparse_tuple_set_nullary(Gecode::EPK_SPARSE, true); + TupleSetNullary sparse_tuple_set_empty(Gecode::EPK_SPARSE, false); + TupleSetNullary dense_tuple_set_nullary(Gecode::EPK_DENSE, true); + TupleSetNullary dense_tuple_set_empty(Gecode::EPK_DENSE, false); + TupleSetNullary dense_compressed_tuple_set_nullary(Gecode::EPK_DENSE_COMPRESSED, true); + TupleSetNullary dense_compressed_tuple_set_empty(Gecode::EPK_DENSE_COMPRESSED, false); SparseTupleSetIncremental sparse_tuple_set_incremental_delta("Delta", 0); SparseTupleSetIncremental sparse_tuple_set_incremental_assign("Assign", 1); SparseTupleSetIncremental sparse_tuple_set_incremental_bool("Bool", 2); diff --git a/test/region.cpp b/test/region.cpp index fa381b51e4..615e34020a 100644 --- a/test/region.cpp +++ b/test/region.cpp @@ -64,6 +64,71 @@ namespace Test { Region r; + /// %Test for growing space memory from an empty block + class SpaceReallocEmpty : public Test::Base { + private: + /// Space without variables + class EmptySpace : public Gecode::Space { + public: + /// Initialize space + EmptySpace(void) {} + /// Constructor for cloning \a s + EmptySpace(EmptySpace& s) : Gecode::Space(s) {} + /// Copy space during cloning + Gecode::Space* + copy(void) override { + return new EmptySpace(*this); + } + }; + + public: + /// Initialize test + SpaceReallocEmpty(void) : Test::Base("Space::Realloc::Empty") {} + /// Perform actual tests + bool + run(void) override { + EmptySpace home; + int* p = home.realloc(static_cast(nullptr), 0, 4); + for (int i = 0; i < 4; i++) + p[i] = i; + const bool grown = (p[3] == 3); + home.free(p, 4); + return grown; + } + }; + + SpaceReallocEmpty space_realloc_empty; + + /// %Test for copying and assigning empty archives + class ArchiveEmpty : public Test::Base { + public: + /// Initialize test + ArchiveEmpty(void) : Test::Base("Archive::Empty") {} + /// Perform actual tests + bool + run(void) override { + Gecode::Archive empty; + Gecode::Archive copy(empty); + if (copy.size() != 0) + return false; + Gecode::Archive full; + full << 1U << 2U; + full = empty; + if (full.size() != 0) + return false; + Gecode::Archive assigned; + assigned = copy; + if (assigned.size() != 0) + return false; + // The copy and the assigned archive stay usable + copy << 3U; + assigned << 4U; + return (copy.size() == 1) && (copy[0] == 3U) && (assigned.size() == 1) && (assigned[0] == 4U); + } + }; + + ArchiveEmpty archive_empty; + } // namespace Test // STATISTICS: test-core From 763e17e8db412911ce4461cd674ca79d44af84af Mon Sep 17 00:00:00 2001 From: Mikael Zayenz Lagerkvist Date: Tue, 3 Nov 2026 22:07:03 +0100 Subject: [PATCH 3/3] State and assert the heap size contract Heap requests now document that allocation sizes are positive, that realloc may grow from zero elements, and that copy needs non-null pointers even for zero elements. Debug builds assert a positive size in Heap::ralloc and rrealloc, and rrealloc no longer accepts zero. Two lint findings are fixed: an intentional copy in the branch tests gets a NOLINT, and an assert in TupleSet finalization documents a count that clang-analyzer cannot follow. Zdev-Change-Id: Z56a1f083f220acb099fd0bc9a9ac161b74b110451fa021068f6b7b92b1e3acca --- changelog.in | 16 +++++++ gecode/int/extensional/tuple-set.cpp | 2 + gecode/support/heap.hpp | 66 ++++++++++++++++++++++++++-- test/branch.cpp | 1 + 4 files changed, 82 insertions(+), 3 deletions(-) diff --git a/changelog.in b/changelog.in index 40a8f6d691..97d69ef0b3 100644 --- a/changelog.in +++ b/changelog.in @@ -207,6 +207,22 @@ Rank: minor A dictionary file holding no accepted word and no final newline requests no heap memory in the crossword and word-square examples. +[ENTRY] +Module: support +What: change +Rank: minor +[DESCRIPTION] +Every request for heap memory must ask for more than zero bytes. Code that +asks the heap for zero bytes, through Heap::ralloc, Heap::rrealloc, or the +typed alloc and realloc, now fails an assertion in Debug builds. Reallocating +from zero objects to a positive number stays valid. Heap::rrealloc no longer +returns a null pointer for size zero; free the block with rfree instead. +[MORE] +The C library may answer a request for zero bytes with a null pointer, which +the heap reports as MemoryExhausted, and reallocating to zero bytes is +implementation-defined in C17. Heap::copy also needs non-null pointers, even +for zero objects, because it passes them to memcpy. + [ENTRY] Module: other What: performance diff --git a/gecode/int/extensional/tuple-set.cpp b/gecode/int/extensional/tuple-set.cpp index 0ef615de98..13a1d023bd 100644 --- a/gecode/int/extensional/tuple-set.cpp +++ b/gecode/int/extensional/tuple-set.cpp @@ -381,6 +381,8 @@ namespace Gecode { support_cursor[i].init(); } for (int a = 0; a < arity; a++) { + // Every position has at least one range and thus a tuple cell + assert(n_ranges > 0U); // Set range pointer vd[a].r = range_cursor; vd[a].base = nullptr; diff --git a/gecode/support/heap.hpp b/gecode/support/heap.hpp index 6d5af56b95..20210c68bc 100644 --- a/gecode/support/heap.hpp +++ b/gecode/support/heap.hpp @@ -72,6 +72,8 @@ namespace Gecode { * * Note that this function implements C++ semantics: the default * constructor of \a T is run for all \a n objects. + * + * The number of objects \a n must be greater than zero. */ template T* alloc(long unsigned int n); @@ -80,6 +82,8 @@ namespace Gecode { * * Note that this function implements C++ semantics: the default * constructor of \a T is run for all \a n objects. + * + * The number of objects \a n must be greater than zero. */ template T* alloc(long int n); @@ -88,6 +92,8 @@ namespace Gecode { * * Note that this function implements C++ semantics: the default * constructor of \a T is run for all \a n objects. + * + * The number of objects \a n must be greater than zero. */ template T* alloc(unsigned int n); @@ -96,6 +102,8 @@ namespace Gecode { * * Note that this function implements C++ semantics: the default * constructor of \a T is run for all \a n objects. + * + * The number of objects \a n must be greater than zero. */ template T* alloc(int n); @@ -140,6 +148,9 @@ namespace Gecode { * \f$\max(n,m)-\min(n,m)\f$ objects, and the destrucor of \a T is * run for all \a n objects in \a b. * + * The new number of objects \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. */ template @@ -153,6 +164,9 @@ namespace Gecode { * \f$\max(n,m)-\min(n,m)\f$ objects, and the destrucor of \a T is * run for all \a n objects in \a b. * + * The new number of objects \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. */ template @@ -166,6 +180,9 @@ namespace Gecode { * \f$\max(n,m)-\min(n,m)\f$ objects, and the destrucor of \a T is * run for all \a n objects in \a b. * + * The new number of objects \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. */ template @@ -179,6 +196,9 @@ namespace Gecode { * \f$\max(n,m)-\min(n,m)\f$ objects, and the destrucor of \a T is * run for all \a n objects in \a b. * + * The new number of objects \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. */ template @@ -186,6 +206,9 @@ namespace Gecode { /** * \brief Reallocate block of \a n pointers starting at \a b to \a m objects of type \a T* from heap * + * The new number of pointers \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. * * This is a specialization for performance. @@ -195,6 +218,9 @@ namespace Gecode { /** * \brief Reallocate block of \a n pointers starting at \a b to \a m objects of type \a T* from heap * + * The new number of pointers \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. * * This is a specialization for performance. @@ -204,6 +230,9 @@ namespace Gecode { /** * \brief Reallocate block of \a n pointers starting at \a b to \a m objects of type \a T* from heap * + * The new number of pointers \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. * * This is a specialization for performance. @@ -213,6 +242,9 @@ namespace Gecode { /** * \brief Reallocate block of \a n pointers starting at \a b to \a m objects of type \a T* from heap * + * The new number of pointers \a m must be greater than zero. The old + * number \a n may be zero. + * * Returns the address of the new block. * * This is a specialization for performance. @@ -225,6 +257,8 @@ namespace Gecode { * Note that this function implements C++ semantics: the assignment * operator of \a T is run for all \a n objects. * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. */ template @@ -235,6 +269,8 @@ namespace Gecode { * Note that this function implements C++ semantics: the assignment * operator of \a T is run for all \a n objects. * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. */ template @@ -245,6 +281,8 @@ namespace Gecode { * Note that this function implements C++ semantics: the assignment * operator of \a T is run for all \a n objects. * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. */ template @@ -255,6 +293,8 @@ namespace Gecode { * Note that this function implements C++ semantics: the assignment * operator of \a T is run for all \a n objects. * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. */ template @@ -262,6 +302,8 @@ namespace Gecode { /** * \brief Copy \a n pointers starting at \a s to \a d * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. * * This is a specialization for performance. @@ -271,6 +313,8 @@ namespace Gecode { /** * \brief Copy \a n pointers starting at \a s to \a d * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. * * This is a specialization for performance. @@ -280,6 +324,8 @@ namespace Gecode { /** * \brief Copy \a n pointers starting at \a s to \a d * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. * * This is a specialization for performance. @@ -289,6 +335,8 @@ namespace Gecode { /** * \brief Copy \a n pointers starting at \a s to \a d * + * Neither \a d nor \a s may be null, even when \a n is zero. + * * Returns \a d. * * This is a specialization for performance. @@ -298,13 +346,23 @@ namespace Gecode { //@} /// \name Raw allocation routines //@{ - /// Allocate \a s bytes from heap + /** + * \brief Allocate \a s bytes from heap + * + * The size \a s must be greater than zero. Debug builds check this + * with an assertion. + */ void* ralloc(size_t s); /// Free memory block starting at \a p void rfree(void* p); /// Free memory block starting at \a p with size \a s void rfree(void* p, size_t s); - /// Change memory block starting at \a p to size \a s + /** + * \brief Change memory block starting at \a p to size \a s + * + * The size \a s must be greater than zero. Debug builds check this + * with an assertion. To release a block, use rfree instead. + */ void* rrealloc(void* p, size_t s); //@} #ifdef GECODE_PEAKHEAP @@ -356,6 +414,7 @@ namespace Gecode { */ forceinline void* Heap::ralloc(size_t s) { + assert(s > 0); #ifdef GECODE_HAS_FAULT_INJECTION Support::FailPoint::check(Support::FailPoint::Phase::HEAP); #endif @@ -393,6 +452,7 @@ namespace Gecode { forceinline void* Heap::rrealloc(void* p, size_t s) { + assert(s > 0); #ifdef GECODE_HAS_FAULT_INJECTION Support::FailPoint::check(Support::FailPoint::Phase::HEAP); #endif @@ -408,7 +468,7 @@ namespace Gecode { _peak = std::max(_peak, _cur); _m.release(); #endif - if (p != nullptr || s == 0) + if (p != nullptr) return p; throw MemoryExhausted(); } diff --git a/test/branch.cpp b/test/branch.cpp index 9236baf5a1..df2d02a760 100644 --- a/test/branch.cpp +++ b/test/branch.cpp @@ -1529,6 +1529,7 @@ namespace Test { namespace Branch { template static bool empty_handle(const Statistics& s) { + // NOLINTNEXTLINE(performance-unnecessary-copy-initialization) Statistics copied(s); Statistics assigned; assigned = s;