From 8be4b0a532bc385a32457bff1bfd4e6070dc02f7 Mon Sep 17 00:00:00 2001 From: Bent Bisballe Nyeng Date: Thu, 6 Jun 2019 09:44:04 +0200 Subject: Store names in deque to make sure the char pointers stay valid. Fix misplaced if(ret). --- getoptpp.hpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/getoptpp.hpp b/getoptpp.hpp index a2dca7f..a363750 100644 --- a/getoptpp.hpp +++ b/getoptpp.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -30,8 +31,9 @@ class Options { /// @param help_text help text for this option /// @param handle lambda that is invoked when the option occures void add(std::string const & name, int has_arg, int* flag, int val, std::string const & help_text, Handle handle) { + names.push_back(name); // create a new option from the args - options.push_back({name.data(), has_arg, flag, val}); + options.push_back({names.back().data(), has_arg, flag, val}); help_texts.push_back(help_text); int index = val; // let val be the option's unique identifier @@ -86,10 +88,10 @@ class Options { // call option's handle ret = handles.at(key)(); } - } - if(ret) { - return ret; + if(ret) { + return ret; + } } for (int i = optind; i < argc; ++i) { @@ -117,6 +119,9 @@ class Options { int index = 0; for(auto const & help_text : help_texts) { + if(index >= (int)options.size()) { + break; + } auto const & opt = options.at(index); std::string args; switch(opt.has_arg) { @@ -151,6 +156,7 @@ class Options { private: std::size_t num_flags{}; std::vector