1

The old code is as below:

 char** wargv = new char*[argc];//memory leak! for(int k = 0; k < argc; ++k) { wargv[k] = new char[strlen(argv[k]) + 1]; strncpy(wargv[k], argv[k], strlen(argv[k])); wargv[k][strlen(argv[k])] = '\0'; } 

because there may cause memory leak, so I want to convert wargv to unique_ptr. How to make it? I know how to convert char* to unique_ptr, the code below works:

int size_t = 10; std::unique_ptr<char[]> wargv(new char[size_t]{0}); strncpy(wargv.get(), "abcdef", size_t); 

but I don't know how to convert char ** to unique_ptr, I tried vector,but it doesn't work.

6
  • 3
    Wouldn't it be better to use std::vector<std::string> instead? Commented Sep 23, 2021 at 7:20
  • See here - stackoverflow.com/questions/31135178/… - using array_ptr_type = std::unique_ptr<char[]>; using array_of_arrays_type = std::unique_ptr<array_ptr_type[]>; Commented Sep 23, 2021 at 7:20
  • I don't want to release the memory manually,the wargv will pass in another function. Commented Sep 23, 2021 at 7:23
  • 1
    You should not use size_t as a variable name. It is a standard type name. Besides, I recommend considering the suggestion of @Someprogrammerdude. Commented Sep 23, 2021 at 8:30
  • Using smart pointers for both "dimensions" will not solve the problem if you want to pass the result to a function expecting a char* arguments. Use standard C++ containers and strings as long as you can, then explicitly convert to the expected only when really needed. Use the (temporary) char** variable. Then explicitly free everything. Commented Sep 23, 2021 at 8:50

1 Answer 1

0

As @Some programmer dude commented, std::vector<std::string> should be a better choice than std::unique_ptr<>, with memory allocation management.

I try to write a simple example and it works well.

#include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { std::vector<std::string> collection(argc); for (auto i = 0; i < argc; i++) { collection[i] = argv[i]; } for (const auto& arg : collection) { std::cout << arg << "\n"; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.