【发布时间】:2010-05-29 03:58:04
【问题描述】:
gcc 4.4.4 c89
我的程序做了很多字符串处理。我不想使用 strncpy 因为它不会终止。而且我不能使用 strlcpy 因为它不可移植。
只是几个问题。我怎样才能让我的功能通过它的步伐,以确保它是完全安全和稳定的。单元测试?
这足以用于生产吗?
size_t s_strlcpy(char *dest, const char *src, const size_t len)
{
size_t i = 0;
/* Always copy 1 less then the destination to make room for the nul */
for(i = 0; i < len - 1; i++)
{
/* only copy up to the first nul is reached */
if(*src != '\0') {
*dest++ = *src++;
}
else {
break;
}
}
/* nul terminate the string */
*dest = '\0';
/* Return the number of bytes copied */
return i;
}
非常感谢您的任何建议,
【问题讨论】:
-
“我怎样才能让我的功能按照它的节奏来确保它完全安全和稳定。单元测试?”是的。
-
James 为什么不将其添加为答案而不是评论? :)
-
是我还是你所有的空值都只有一个'l'?缺少“l”是怎么回事?
-
NULL 是指针,nul 是字符'\O'。
-
如果你有强迫症,你可能可以证明这样一个函数的正确性。
标签: c