Re: vector<string> to char*[]
* Andrew Wingorodov:
Joel Yliluoma <bisqwit@iki.fi> wrote:
const char** argv = new const char*[ arg.size() ];
for(size_t a=0; a<arg.size(); ++a) argv[a] = arg[a].c_str();
execv(... argv ...);
// cleanup when error happened
delete[] argv;
i do correct?
//
const char**
args::constchar (const std::vector<std::string>& arg_)
{
static std::auto_ptr<const char*> v;
v = (std::auto_ptr<const char*>) new const char* [arg_.size()+1];
auto_ptr calls delete, whereas you need delete[]. Not that it matters
much in practice for a char array. But formally UB.
std::vector<std::string>::const_iterator i = arg_.begin();
size_t j;
for (; i != arg_.end (); ++i)
{
v.get()[j++] = (*i).c_str() ;
}
v.get()[j] = NULL;
return v.get();
}
When the function returns, the auto_ptr calls delete. As mentioned
that's just formally UB, but if that delete works, the effect is that
the function returns a pointer to deallocated memory.
Try what I posted earlier, it's safe:
std::vector<string> arg;
...
std::vector<char const*> v( arg.size() );
for( size_t i = 0; i < v.size(); ++i ) { v[i] = arg[i].c_str(); }
blahblah( &v[0] );
If you have any questions, just ask.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?