1

I was think something like:

const char * res[cnt];
int i = 0;
for (auto mystring : strings) {
    const char * str = mystring.c_str();
    res[i++] = str;
}

//then pass res as const char **

But it occurred to me that 'str' is a local variable, the address stored in res could be invalid? What is the right way to do so?

6
  • 1
    the contents of the loop are semanticall incorrect as you fill the array with a bunch of dangling pointers Commented May 30, 2021 at 13:39
  • It would improve the question to show a complete program. The answer very much depends on what strings is, what its lifetime is, and what you are going to do with res. and what cnt is Commented May 30, 2021 at 13:40
  • 1
    You're making copies of the strings with auto instead of auto &, so there may indeed be an issue. Commented May 30, 2021 at 13:40
  • Note that this isn't "converting" the strings, just putting their internal string addresses into the other array. This creates an issue: when the strings have to reallocate and thus possibly change their address as a result, the pointers in the arrays may become dangling pointers. Example: godbolt.org/z/fvob3hfxT Commented May 30, 2021 at 13:49
  • @mediocrevegetable1 thanks I see the risk. But what is the right way? I just want to pass these strings and they will be processed. The problem is I need to pass a const char ** since API limitation.. Commented May 30, 2021 at 14:09

1 Answer 1

4

The problem has nothing to do with str, which will be destroyed after iteration, but this doens't mean the char array pointed by it will be destroyed too.

The problem is mystring is declared as by-copy, it'll be destroyed after iteration, then the char arrays returned by c_str get destroyed too. Pointers assigned into res become dangling.

You can change mystring as reference (to const), e.g.

for (auto const & mystring : strings) {
    const char * str = mystring.c_str();
    res[i++] = str;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.