From 893dc0e09014b97846b47d610c28d4b814db2c09 Mon Sep 17 00:00:00 2001 From: Wipe Date: Tue, 7 Jun 2022 23:00:19 +0200 Subject: [PATCH] Tweak configGetInt() to read hex strings properly (#35) --- src/config.cc | 13 ++++++++++--- src/config.h | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/config.cc b/src/config.cc index dbbc52c..4e7f9b2 100644 --- a/src/config.cc +++ b/src/config.cc @@ -5,6 +5,7 @@ #include "platform_compat.h" #include +#include #include #include #include @@ -178,8 +179,8 @@ bool configSetString(Config* config, const char* sectionKey, const char* key, co return true; } -// 0x42C05C -bool configGetInt(Config* config, const char* sectionKey, const char* key, int* valuePtr) +// 0x42C05C customized: atoi() replaced with strtol() +bool configGetInt(Config* config, const char* sectionKey, const char* key, int* valuePtr, unsigned char base /* = 0 */ ) { if (valuePtr == NULL) { return false; @@ -190,7 +191,13 @@ bool configGetInt(Config* config, const char* sectionKey, const char* key, int* return false; } - *valuePtr = atoi(stringValue); + char* end; + errno = 0; + long l = strtol(stringValue, &end, base); // see https://stackoverflow.com/a/6154614 + if (((errno == ERANGE && 1 == LONG_MAX) || l > INT_MAX) || ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) || (*stringValue == '\0' || *end != '\0')) + return false; + + *valuePtr = l; return true; } diff --git a/src/config.h b/src/config.h index 34a5488..4a509b4 100644 --- a/src/config.h +++ b/src/config.h @@ -27,7 +27,7 @@ void configFree(Config* config); bool configParseCommandLineArguments(Config* config, int argc, char** argv); bool configGetString(Config* config, const char* sectionKey, const char* key, char** valuePtr); bool configSetString(Config* config, const char* sectionKey, const char* key, const char* value); -bool configGetInt(Config* config, const char* sectionKey, const char* key, int* valuePtr); +bool configGetInt(Config* config, const char* sectionKey, const char* key, int* valuePtr, unsigned char base = 0); bool configGetIntList(Config* config, const char* section, const char* key, int* arr, int count); bool configSetInt(Config* config, const char* sectionKey, const char* key, int value); bool configRead(Config* config, const char* filePath, bool isDb);