JAM AICA JAM AICA - 1 year ago 106
C Question

Exec fails due to Bad Address

I have a serious problem with exec.I've tried both options with list(execl) and array(execv) but the problem remains.I'll give the function in which i try to make the call.

#include <unistd.h>
#include <sys/types.h>
void MyFunc(string aparams[],char* infile,char* outfile,int k,int points){

int mcount=3;
char* offset= new char[5];
char* pntr=new char[5];
char* *wparams=new char*[mcount];
for (int i = 0; i < mcount; i++) {
wparams[i] = new char[aparams[i].length() + 1];
strcpy(wparams[i], aparams[i].c_str());
char *cwd;
cout << cwd << endl;
execl(cwd,wparams[0],"-i",infile,"-o",outfile,"-f",offset,"-n",pntr,"-a",wparams[1],wparams[2],wparams[3],(char*) NULL);

cout << "exec failed" << endl;
perror("The problem in exec is:");


aparams[0] contains a string with the name of an executable file,let's say "test".I compiled -> g++ test.cpp -o test -> so I got this executable.
The other positions of aparams contain some arguments for the test program.

So,test never runs(when I run it from command line it's ok) and perror shows the message "The problem in exec is: Bad Address."

I've also tried to cast all arguments(const char*) but nothing changed.
Is it a problem with arguments? Or it's a matter of the executable?

Answer Source

mcount is 3, so wparams points to an array with three elements - wparams[0], wparams[1] and wparams[2].

Then you access wparams[3] which is invalid and contains garbage.

Don't try to access array elements that don't exist.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download