为什么这两个字符数组不能正确连接?(C 编程)

why these two character arrays won't concatenate properly?(C Programming)

char *program_working_dir;
char backup_dir[9]="/Backups/";

// getting the current working directory
program_working_dir = getcwd(NULL, 0);
if (program_working_dir == NULL){
    printf("Failed to get working directory( take_backup function )\n");
    return -1;
}

// allocate memory for full path that contain the current directory and the /Backups/
char *full_backup_dir = (char *)malloc( (strlen(program_working_dir) + strlen(backup_dir) + 1 ) * sizeof(uint8_t) );
if (full_backup_dir == NULL){
    printf("Failed to allocate proper memory to stor full path of backup directory\n");
    return -1;
}

// used for debugging purposes
printf("program working dir%s\n", program_working_dir); // (here : /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/)
printf("%d\n",  strlen(program_working_dir));  // ( 86 length of program_working_dir )

// try to concatenate the tow string using snprintf. I add 1 to size for '[=10=]' terminate string
snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1  ) * sizeof(uint8_t)  , "%s%s", program_working_dir, backup_dir);
printf("Full path: %s\n", full_backup_dir);

这里我只是尝试将两个字符串(路径)连接在一起,但有时我执行此操作时它无法正常工作。例如我得到这个:

program working dir/home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing
86
path /home/ramixix/Documents/3_grade/2th_Semester/image_processing/Project/image_processing/Backups/��M�X

正如您在此处看到的,连接后我得到了有线字符串 /�M�X,这毁了我所有的程序,我不明白为什么会这样。 我也尝试使用 strncpy 和 strncat 做同样的事情,所以我替换了行:

snprintf(full_backup_dir, ( strlen(program_working_dir) + strlen(backup_dir) +1  ) * sizeof(char)  , "%s%s", program_working_dir, backup_dir);

strcpy(full_backup_dir, program_working_dir);
strcat(full_backup_dir, backup_dir);

还是一样的问题。我还删除了我添加到 full_back_dir 大小的 1,但此程序再次不想 运行 正确。在这一点上,我真的很感激任何帮助和反馈。请帮助!!!!

这个数组

char backup_dir[9]="/Backups/";

不包含字符串,因为它 space 不足以存储用作初始值设定项的字符串文字的终止零“\0”。

像这样声明数组

char backup_dir[] = "/Backups/";

实际上使用函数strlen不需要计算存储字符串的长度。等于sizeof( backup_dir ) - 1.

也在这个表达式中

 (strlen(program_working_dir) + strlen(backup_dir) + 1 ) * sizeof(uint8_t)

操作数 sizeof(uint8_t) 是多余的,只会让代码的读者感到困惑。

上面的表达式可以这样写

strlen( program_working_dir ) + sizeof( backup_dir )