【问题标题】:Bad behavior with strcatstrcat 的不良行为
【发布时间】:2015-02-17 02:06:07
【问题描述】:

为了复制目录,我实现了以下功能。

int copy_dir(char *source, char *destination, char *file_name)
{
    DIR *dir_ptr = NULL;
    struct dirent *direntp;
    char temp_dest[strlen(destination)+1];
    char temp_src[strlen(source)+1];
    strcat(destination, "/");
    strcat(source, "/");
    strcpy(temp_dest, destination);
    strcpy(temp_src, source);

    ...

    if( (dir_ptr = opendir(source)) == NULL )
    {
        fprintf(stderr, "Cannot open %s for copying\n", source);
        return ERR_OPEN_DIR;
    }
    else
    {
        while(direntp = readdir(dir_ptr))
        {     
            // File must already be on the USB key
            if(strcmp(direntp->d_name,file_name) == 0)
            {               
                strcat(temp_dest, direntp->d_name);
                printf("after strcat temp_dest=%s\n", temp_dest);         
                strcat(temp_src, direntp->d_name);
                printf("after strcat temp_src=%s\n", temp_src); 
                printf("destination:%s\n",temp_dest);
                copy_files(temp_src, temp_dest); 
            }
        }
    }
    closedir(dir_ptr);
    return 1;
} 

我想了解为什么下面的实现

strcat(temp_dest, direntp->d_name);
printf("after strcat temp_dest=%s\n", temp_dest);         
strcat(temp_src, direntp->d_name);
printf("after strcat temp_src=%s\n", temp_src); 
printf("destination:%s\n",temp_dest);
copy_files(temp_src,temp_dest);

返回:

after strcat temp_dest=/tmp/usb/test10
after strcat temp_src=/media/sda1/test10
destination:10

为什么通过最后一个 printf 返回 10 而不是 /tmp/usb/test10 ?

【问题讨论】:

  • 你的temp_dest声明和初始化在哪里?
  • 如果您不介意,可以提供MCVE吗?
  • @Sourav Ghosh - 我不知道 MCVE 是什么意思?您可以发送完整的表格吗?
  • 对不起,我编辑了我的第一篇文章并包含了整个功能
  • @bhuvanesh 那里有一个链接。对于 OP:在本次比赛中,这意味着您提供了一个可以编译和执行的最小程序(即,不仅是完整的功能,还包括主文件和头文件)。这让人们更容易自己尝试并找出错误。

标签: c variables parameters parameter-passing strcat


【解决方案1】:

这是你的主要问题,首先你不应该修改char *sourcechar *destination,因为你不知道是否有足够的空间来追加一个字符,而strcat不会为你分配它,但是最重要的错误是这个

首先你声明这些数组保存strlen(string) + 1字符,这实际上意味着你只能将相同的字符串复制到它们中,因为你需要一个额外的字符来终止'\0'字节,strlen不计算在内/p>

char temp_dest[strlen(destination)+1];
char temp_src[strlen(source)+1];

然后你在字符串中追加一个字符,这个字符没有被strlen 计算在内,所以现在字符串不适合你的数组,而且你不知道destinationsource 是否足够多一个字符的空间。

strcat(destination, "/");
strcat(source, "/");

最后你复制字符串

strcpy(temp_dest, destination);
strcpy(temp_src, source);

我建议你这样做

size_t dest_length = strlen(destination);
size_t src_length = strlen(source);
char temp_dest[dest_length+2];
char temp_src[scr_length+2];

temp_dest[dest_length] = '/';
temp_src[src_length] = '/';
temp_dest[1 + dest_length] = '\0';
temp_src[1 + src_length] = '\0';

memcpy(temp_dest, destination, dest_length);
memcpy(temp_src, source, src_length);

【讨论】:

    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多