jeudi 23 septembre 2021

how to convert char ** to unique_ptr array?

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.

Aucun commentaire:

Enregistrer un commentaire