What's different about this variable assignment?
The following code attempts to put the contents of string c into arg[0].
const char **argv = new const char* [paramlist.size() + 2];
argv[0] = c.c_str();
This is another way to do it.
argv[0] = "someprogram"
I am noticing that later in my program, 开发者_JAVA技巧the second way works, but the first way causes an error. What could possibly be different? How could the first way be changed so that it works right?
This is where the problem occurs:
execvp(c.c_str(), (char **)argv);
If I change it to the following, then the problem doesn't occur. Why is that?
execvp(argv[0], (char **)argv);
In both ways you keep const char*
pointers in argv[0]
. So the only concern is whether pointers are valid and point to zero-terminated string.
"someprogram" pointer is valid and point to zero-terminated string during program execution.
c.c_str()
pointer is guaranteed to be valid from the moment it is returned (by std::basic_string::c_str() function) to the moment string c
is changed or destroyed. So if you access string c
explicitly or implicitly with any non-const function (including its destructor) the pointer you stored into argv[0]
will likely become invalid.
ADD:
Obviously to make argv[0] = c.c_str();
variant work correctly you have to just use argv
only in the scope of std::string c
(where c
exist) and don't change c
in any way after you make this assignment (argv[0] = c.c_str();
).
You can use _strdup
:
const char **argv = new const char* [paramlist.size() + 2];
argv[0] = _strdup(c.c_str());
_strdup
allocates memory to store the copy of the string. When you are finished with the string, use free()
to return the memory.
The _strdup
function looks something like this:
char *_strdup (const char *s) {
char *d = (char *)(malloc (strlen (s) + 1));
if (d == NULL) return NULL;
strcpy (d,s);
return d;
}
精彩评论