strcat 异常工作

strcat working paranormally

我正在尝试传递命令行参数,然后我将这些参数适当地连接起来以生成 shell 命令,以便我可以 运行 使用 system() (我知道这是不可取的,并且有更好的方法,但我被要求仅以这种方式进行)。但是我传递的字符串的连接存在一些问题 这是代码(我在每一步都打印了所有内容以获得清晰的理解,不,我还没有编写 system() 调用,首先我需要对这个连接进行排序):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
     char* path=argv[1];
     char* oldName=argv[2];
     char* newName=argv[3];
     char* command1="cd "; 
     char* command2="ren ";
      printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(command1,path);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(oldName," ");
    strcat(oldname,newName);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(command2,oldName);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);

    return 0;
}

然而,在将 command1 连接到路径后,一切都变得一团糟。

strcat 通过将字节从源字符串复制到目标字符串的末尾来工作。问题是您的目标字符串是:

  1. 常量字符串(并且可能不在可写内存中)
  2. 不够长,无法容纳整个结果

您可能应该创建一个像 char buffer[1024] 这样的字符缓冲区来保存命令并使用 snprintf 将命令格式化到缓冲区中。

strcat 期望目标足够大以容纳结果。至 quote:

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

您需要使用字符缓冲区分配 space 以防止 strcat 崩溃,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
    char* path=argv[1];
    char oldName[256];
    char* newName=argv[3];
    char command1[256];
    char command2[256];
    strcpy(command1, "cd ");
    strcpy(command2, "ren ");
    strcpy(oldName, argv[2]);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(command1,path);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(oldName," ");
    strcat(oldName,newName);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);
    strcat(command2,oldName);
    printf("\n\n%s\n%s\n%s\n%s\n%s\n",command1,command2,path,oldName,newName);

    return 0;
}