Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix undefined behaviour in nlopt_result_from_string #409

Merged
merged 2 commits into from
Dec 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/api/general.c
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,8 @@ const char *nlopt_result_to_string(nlopt_result result)
case NLOPT_XTOL_REACHED: return "XTOL_REACHED";
case NLOPT_MAXEVAL_REACHED: return "MAXEVAL_REACHED";
case NLOPT_MAXTIME_REACHED: return "MAXTIME_REACHED";
case NLOPT_NUM_RESULTS: return NULL;
default: return NULL;
}
return NULL;
}


Expand All @@ -196,9 +195,10 @@ nlopt_result nlopt_result_from_string(const char * name)
int i;
if (name == NULL)
return -1;
for (i = 0; i < NLOPT_NUM_RESULTS; ++i)
{
if (strcmp(name, nlopt_result_to_string(i)) == 0)
/* Check all valid negative (failure) and positive (success) result codes */
for (i = NLOPT_NUM_FAILURES + 1; i < NLOPT_NUM_RESULTS; ++i) {
const char *name_i = nlopt_result_to_string(i);
if (name_i != NULL && strcmp(name, name_i) == 0)
return i;
}
return -1;
Expand Down
3 changes: 2 additions & 1 deletion src/api/nlopt.h
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,14 @@ typedef enum {
NLOPT_OUT_OF_MEMORY = -3,
NLOPT_ROUNDOFF_LIMITED = -4,
NLOPT_FORCED_STOP = -5,
NLOPT_NUM_FAILURES = -6, /* not a result, just the number of possible failures */
NLOPT_SUCCESS = 1, /* generic success code */
NLOPT_STOPVAL_REACHED = 2,
NLOPT_FTOL_REACHED = 3,
NLOPT_XTOL_REACHED = 4,
NLOPT_MAXEVAL_REACHED = 5,
NLOPT_MAXTIME_REACHED = 6,
NLOPT_NUM_RESULTS /* not a result, just the number of them */
NLOPT_NUM_RESULTS /* not a result, just the number of possible successes */
} nlopt_result;

/* nlopt_result enum <-> string conversion */
Expand Down