Exec由于地址错误而失败

时间:2016-11-22 01:51:38

标签: c++ c exec unistd.h execl

我有一个严重的exec问题。我已经尝试了list(execl)和array(execv)两个选项,但问题仍然存在。我将给出我尝试进行调用的函数。

#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]包含一个带有可执行文件名称的字符串,让我们说“test”.I编译 - &gt; g ++ test.cpp -o test - &gt;所以我有了这个可执行文件 aparams的其他位置包含测试程序的一些参数。

因此,测试永远不会运行(当我从命令行运行它没关系)并且perror显示消息“exec中的问题是:地址错误。”

我也尝试过抛出所有参数(const char *)但没有改变。 这是参数的问题吗?或者这是可执行文件的问题?

2 个答案:

答案 0 :(得分:2)

mcount为3,因此wparams指向包含三个元素的数组 - wparams[0]wparams[1]wparams[2]

然后你访问无效的wparams[3]并包含垃圾。

不要尝试访问不存在的数组元素。

答案 1 :(得分:1)

你的问题在这一行:

execl(cwd, 
    wparams[0], 
    "-i", infile, "-o", outfile, "-f", offset, "-n", pntr, 
    "-a", wparams[1], wparams[2], wparams[3], (char*) NULL);    

你正试图发送不存在的wparams [3]!它是wparam数组的第4个元素,您在变量mcount的初始化中明确将其定义为数组[3]。