Skip to content

Commit

Permalink
Dynamically allocate space in Horner_tree if WorkSpace is too small.
Browse files Browse the repository at this point in the history
There is no need to use the WorkSpace specifically for the sorting. If
it is too small, just allocate a new buffer and free it after.
  • Loading branch information
jodavies committed Jun 5, 2024
1 parent 83e3d41 commit d5413c8
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions sources/optimize.cc
Original file line number Diff line number Diff line change
Expand Up @@ -870,20 +870,22 @@ vector<WORD> Horner_tree (const WORD *expr, const vector<WORD> &order) {
}

// sort variables in individual terms using bubble sort
WORD *sorted = AT.WorkPointer;
WORD* sorted;
WORD* dynamicAlloc = 0;
LONG sumsize = 0;

for (const WORD *t=expr; *t!=0; t+=*t) {
sumsize += *t;
}
if ( sorted + sumsize > AT.WorkTop ) {
MLOCK(ErrorMessageLock);
MesPrint("=== Workspace overflow. %l bytes is not enough.",AM.WorkSize);
MesPrint("=== Change parameter WorkSpace in %s",setupfilename);
sumsize = (AT.WorkPointer-AT.WorkSpace+sumsize)*sizeof(WORD);
MesPrint("=== At least %l bytes are needed.",sumsize);
MUNLOCK(ErrorMessageLock);
Terminate(-1);

// We actually need sumsize + 1 WORDS available, due to the "*sorted = 0;"
// at the end of the sort loop.
if ( AT.WorkPointer + sumsize + 1 > AT.WorkTop ) {
dynamicAlloc = (WORD*)Malloc1(sizeof(*dynamicAlloc)*(sumsize+1), "Horner_tree alloc");
sorted = dynamicAlloc;
}
else {
sorted = AT.WorkPointer;
}

for (const WORD *t=expr; *t!=0; t+=*t) {
Expand Down Expand Up @@ -919,7 +921,12 @@ vector<WORD> Horner_tree (const WORD *expr, const vector<WORD> &order) {
}

*sorted = 0;
sorted = AT.WorkPointer;
if ( dynamicAlloc ) {
sorted = dynamicAlloc;
}
else {
sorted = AT.WorkPointer;
}

// find pointers to all terms and sort them efficiently
vector<const WORD *> terms;
Expand Down Expand Up @@ -957,6 +964,10 @@ vector<WORD> Horner_tree (const WORD *expr, const vector<WORD> &order) {
}
res.resize(j);

if ( dynamicAlloc ) {
M_free(dynamicAlloc, "Horner_tree alloc");
}

#ifdef DEBUG
MesPrint ("*** [%s, w=%w] DONE: Horner_tree(%a)", thetime_str().c_str(), order.size(), &order[0]);
#endif
Expand Down

0 comments on commit d5413c8

Please sign in to comment.