c++14 - Customize the deleter to deallocate a 2D array through std::unique_ptr -
suppose parsing environment variable list given map<string, string>
2d memory held unique_ptr<char*[]>
. however, not sure how can customise deleter 2d memory case ?
// given: env (type of map<string, string>) // return: unique_ptr<char*[]> (with customized deleter) // prepare parsing environment c-style strings auto idx = size_t{0}; // should fill `ret` proper deleter won't give memory leak? auto ret = std::make_unique<char*[]>(env.size() + 1, ???); for(const auto& kvp : env) { auto entry = kvp.first + "=" + kvp.second; ret[idx] = new char[entry.size() + 1]; strncpy(ret[idx], entry.c_str(), entry.size() + 1); ++idx; } ret[idx] = nullptr; // later use of exec call return ret;
apparently, above code leaks, because of new operator
in inner loop.
there no version of std::make_unique
accepting deleter argument (by way, std::make_unique
c++14, not c++11). try this:
size_t size = env.size() + 1; auto ret = std::unique_ptr<char*, std::function<void(char**)> >( new char* [size], [size](char** ptr) { for(size_t i(0); < size; ++i) { delete[] ptr[i]; } delete[] ptr; } );
you can pass ret.get()
execvpe.
Comments
Post a Comment