JAM AICA JAM AICA - 12 days ago 5
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];
sprintf(offset,"%d",k);
char* pntr=new char[5];
sprintf(pntr,"%d",points);
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;
cwd=(char*)malloc(255);
getcwd(cwd,255);
strcat(cwd,"/");
strcat(cwd,wparams[0]);
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:");
exit(3);


}

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

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.

Comments