I have been trying to avoid using char ** arrays, however because i am using execvp, i wrote a method to convert a vector of strings to a null terminated char **.
Unfortunately i have until recently been getting segmentation faults, which makes me suspicious that my method doesn't always work for one reason or another:
void vectorToNullArray(std::vector<std::string> const &v, char **a) {
int i = 0;
while (i < v.size()) {
std::string str = v[i];
char *cstr = new char[str.size()+1];
strcpy(cstr, str.c_str());
a[i] = cstr; // <-- segfault here
i++;
}
a[i] = nullptr;
}
if i can be completely free of char ** in the first place, that would be ideal. Why is this code segfaulting?
EDIT: this is how i call it:
char **argvA;
vectorToNullArray(_ARGV, argvA);
where _ARGV
is an std::vector<std::string>
, a member variable of some class.
EDIT 2: working solution
std::vector<char *> nullTerminatedArgV(std::vector<std::string> const &v) {
std::vector<char *> result;
for (auto const &s : v) {
result.push_back(const_cast<char *>(s.c_str()));
}
result.push_back(nullptr);
return result;
}
usage with execvp:
std::vector<char *> argv = nullTerminatedArgV(_ARGV);
char **command = argv.data();
int status = execvp(command[0], command);
perror("execvp error");
essentially the accepted answer, with additions from here: