I’ve got a plugin system in my project (running on linux), and part of this is that plugins have a “run” method such as:
void run(int argc, char* argv[]);
I’m calling my plugin and go to check my argv array (after doing a bunch of other stuff), and
the array is corrupted. I can print the values out at the top of the function, and they’re correct, but not later on in the execution. Clearly something is corrupting the heap, but
I’m at a loss of how I can try to pin down exactly what’s overwriting that memory. Valgrind hasn’t helped me out much.
Sample code by request:
My plugin looks something like this:
void test_fileio::run(int argc, char* argv[]) {
bool all_passed = true;
// Prints out correctly.
for (int ii=0; ii < argc; ii++) {
printf("Arg[%i]: %s\n", ii, argv[ii]);
}
<bunch of tests snipped for brevity>
// Prints out inccorrectly.
for (int ii=0; ii < argc; ii++) {
printf("Arg[%i]: %s\n", ii, argv[ii]);
}
}
This is linked into a system that exposes it to python so I can call these plugins as python functions. So I take a string parameter to my python function and break that out thusly:
char** translate_arguments(string args, int& argc) {
int counter = 0;
vector<char*> str_vec;
// Copy argument string to get rid of const modifier
char arg_str[MAX_ARG_LEN];
strcpy(arg_str, args.c_str());
// Tokenize the string, splitting on spaces
char* token = strtok(arg_str, " ");
while (token) {
counter++;
str_vec.push_back(token);
token = strtok(NULL, " ");
}
// Allocate array
char** to_return = new char*[counter];
for (int ii=0; ii < counter; ii++)
to_return[ii] = str_vec[ii];
// Save arg count and return
argc = counter;
return to_return;
}
The resulting argc and argv is then passed to the plugin mentioned above.
How does
translate_argumentsget called? That is missing…Does it prepare an array of pointers to chars before calling the
runfunction in the plugin, since therunfunction has parameterchar *argv[]?This looks like the line that is causing trouble…judging by the code
You are intending to allocate a pointer to pointer to chars, a double pointer, but it looks the precedence of the code is a bit mixed up?
Have you tried it this way:
Also, in your for loop as shown…you are not allocating space for the string itself contained in the vector…?
for (int ii=0; ii < counter; ii++) to_return[ii] = str_vec[ii]; // Should it be this way...??? for (int ii=0; ii < counter; ii++) to_return[ii] = strdup(str_vec[ii]);At the risk of getting downvoted as the OP did not show how the
translate_argumentsis called and lacking further information….and misjudging if my answer is incorrect…Hope this helps,
Best regards,
Tom.