1

我决定制作一个包装器,strncpy因为我的源代码需要我做很多字符串副本。如果源等于或大于目标,我想确保字符串终止。

这段代码将在生产中使用,所以我只想看看使用这个包装器是否有任何潜在的危险。

我以前从未做过包装,所以我试图让它变得完美。

非常感谢您的任何建议,

/* Null terminate a string after coping */
char* strncpy_wrapper(char *dest, const char* source, 
                      const size_t dest_size, const size_t source_size)
{
    strncpy(dest, source, dest_size);
    /* 
     * Compare the different length, if source is greater
     * or equal to the destination terminate with a null.
     */
    if(source_size >= dest_size)
    {
        dest[dest_size - 1] = '\0';
    }

    return dest;
}

====编辑更新====

/* Null terminate a string after coping */
char* strncpy_wrapper(char *dest, const char* source, 
                      const size_t dest_size)
{
    strncpy(dest, source, dest_size);
    /* 
     * If the destination is greater than zero terminate with a null.
     */
    if(dest_size > 0)
    {
        dest[dest_size - 1] = '\0';
    }
    else
    {
        dest[0] = '\0'; /* Return empty string if the destination is zero length */
    }

    return dest;
}
4

5 回答 5

3

您无需检查源是否大于目标,只需始终将目标中的最后一个字符设为“\0”。

于 2009-07-26T11:27:00.377 回答
2

在访问数组之前检查dest_size否则你会遇到麻烦:

if (dest_size > 0) {
    dest[dest_size - 1] = '\0';
}

其实,现在想起来,还是直接死吧:

if (dest_size == 0) {
    fputs(stderr, "strncpy(x,y,0)");
    exit(1);
}

否则,您将遇到与原始strncpy()相同的问题,如果dest_size为 0 ,则dest可能不会被终止。

于 2009-07-26T11:44:06.473 回答
2

您应该研究半标准 BSD 函数strlcpy()strlcat().

您应该考虑 ISO TR24731 等功能strncpy_s()是否合适并且在您需要的地方可用。

于 2009-07-26T14:54:12.797 回答
1

如果您对缓冲区的分配没有任何限制,strndup可能更合适。

它将分配和复制最多len字符,并始终以 NULL 终止。

于 2009-07-26T12:06:11.467 回答
1

如果 dest_size 是要复制的字符数,而 source_size 是源字符串中的字符数。
你应该试试这个:


 size_t numchars = dest_size > source_size ? source_size : dest_size;
 strncpy(dest,source,numchars) ;
 dest[numchars] = 0 ;
于 2009-07-26T12:27:24.143 回答