【发布时间】:2012-06-22 20:34:25
【问题描述】:
我已经阅读了几个论坛,但找不到解决这个问题的方法。
int sIndex = 3;
char serverArgs[serverCommandCount + 3][20];
strcpy(serverArgs[0], "ant");
strcpy(serverArgs[1], "-f");
strcpy(serverArgs[2], "/dev/server1/trunk/build.xml");
if(serverStop){strcpy(serverArgs[sIndex], "jboss-stop"); sIndex++;}
if(serverClean){strcpy(serverArgs[sIndex], "clean"); sIndex++;}
if(serverDeploy){strcpy(serverArgs[sIndex], "deploy"); sIndex++;}
if(releaseDB){strcpy(serverArgs[sIndex], "releasedb"); sIndex++;}
if(createDB){strcpy(serverArgs[sIndex], "createdb"); sIndex++;}
if(serverStart){strcpy(serverArgs[sIndex], "jboss-start"); sIndex++;}
if(serverDebug){strcpy(serverArgs[sIndex], "jboss-start-debug"); sIndex++;}
execv(antEx, serverArgs);
在这个解决方案中,问题是 execv 想要一个 char *[ ] 而不是 char[ ]。
int sIndex = 3;
char *serverArgs[serverCommandCount + 3];
for(index = 0; index < serverCommandCount + 3; index++)
serverArgs[index] = malloc(20);
strcpy(serverArgs[0], "ant");
strcpy(serverArgs[1], "-f");
strcpy(serverArgs[2], "/dev/server1/trunk/build.xml");
if(serverStop){strcpy(serverArgs[sIndex], "jboss-stop"); sIndex++;}
if(serverClean){strcpy(serverArgs[sIndex], "clean"); sIndex++;}
if(serverDeploy){strcpy(serverArgs[sIndex], "deploy"); sIndex++;}
if(releaseDB){strcpy(serverArgs[sIndex], "releasedb"); sIndex++;}
if(createDB){strcpy(serverArgs[sIndex], "createdb"); sIndex++;}
if(serverStart){strcpy(serverArgs[sIndex], "jboss-start"); sIndex++;}
if(serverDebug){strcpy(serverArgs[sIndex], "jboss-start-debug"); sIndex++;}
execv(antEx, serverArgs);
当我以这种方式尝试时,当它尝试执行时出现分段错误
strcpy(serverArgs[1], "-f");
我错过了什么?
【问题讨论】:
-
我也试过这个没有malloc。
-
strcpy(serverArgs[2], "/dev/server1/trunk/build.xml");行可能不好 -- 该字符串大于 20 个字符。 -
@Peter 您应该将其添加为答案(而不是对问题的评论)。
-
另一件需要注意的事情:
strcpy的使用通常是不受欢迎的,正是因为这个原因——创建缓冲区溢出太容易了。使用strncpy并提供明确的长度。 -
@JustinSpahr-Summers,
strncpy可能比strcpy更“不受欢迎”,因为您必须注意结果总是以 nul 终止。