Call a c program from C++ and pass arguments -
i have c++ program, , @ point in program need call c program , pass arguments it.
i working in linux env.
the file simpsh compiled c file in same dir. resulting_simpsh_command string data of type --creat --trunc --wronly f1 , far.
when check values recieve in c program, shows instead
void execute_simpsh(string resulting_simpsh_command) { pid_t pid = fork(); if(pid == -1) perror("fork failed!"); else if(pid ==0) { char* args[256]; string simpsh ="./simpsh"; args [0] = (char*) simpsh.c_str(); string temp_option_holder=""; int nextcommand=1; for(int i=0;i<resulting_simpsh_command.length();i++) { if(resulting_simpsh_command[i] !=' ') { temp_option_holder += resulting_simpsh_command[i]; } else { cout<<"saving argument: "<<temp_option_holder<<endl; args [nextcommand] = (char*) temp_option_holder.c_str(); temp_option_holder=""; nextcommand +=1; } } cout<<"command numbers "<<nextcommand<<endl; args [nextcommand + 1] = null; if(execvp(args[0],args) == -1) cout<<"failed open simpsh, maybe didnt compile?"<<endl; exit(1); } else { //not important } }
a lot of args
array invalid pointers due (mis)use of c_str
.
pointer becomes invalid string's buffer reallocated.
of args
pointers point same thing though they're valid.
two options fixing (off top of head):
dynamic allocation:
args[nextcommand] = strdup(temp_option_holder.c_str());
which requires deallocation later.
or, if can live limiting argument length, can use array , avoid memory management (but need worry overflows instead):
char arg_strings[256][argument_length] = {0}; char* args[256] = {0}; // ... assert(temp_option_holder.length() < argument_length); strncpy(arg_strings[nextcommand], temp_option_holder.c_str(), argument_length); args[nextcommand] = arg_strings[nextcommand];
Comments
Post a Comment