strncpy可以替代strcpy来防止缓冲区越界。
但是如果还要考虑运行效率的话,也许strlcpy是一个更好的方式。
1. strcpy
我们知道,strcpy 是依据 /0 作为结束判断的,如果 to 的空间不够,则会引起 buffer overflow。strcpy 常规的实现代码如下(来自 OpenBSD 3.9):
char *
strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != '/0'; ++from, ++to);
return(save);
}
但通常,我们的 from 都来源于用户的输入,很可能是非常大的一个字符串,因此 strcpy 不够安全。
2. strncpy
在 ANSI C 中,strcpy 的安全版本是 strncpy。
char *strncpy(char *s1, const char *s2, size_t n);
但 strncpy 其行为是很诡异的(不符合我们的通常习惯)。标准规定 n 并不是 sizeof(s1),而是要复制的 char 的个数。一个最常见的问题,就是 strncpy 并不帮你保证 /0
结束。
char buf[8];
strncpy( buf, "abcdefgh", 8 );
看这个程序,buf 将会被 "abcdefgh" 填满,但却没有 /0 结束符了。
另外,如果 s2 的内容比较少,而 n 又比较大的话,strncpy 将会把之间的空间都用 /0 填充。这又出现了一个效率上的问题,如下:
char buf[80];
strncpy( buf, "abcdefgh", 79 );
上面的 strncpy 会填写 79 个 char,而不仅仅是 "abcdefgh" 本身。
strncpy 的标准用法为:(手工写上 /0)
strncpy(path, src, sizeof(path) - 1);
path[sizeof(path) - 1] = '/0';
len = strlen(path);
3. strlcpy
// Copy src to string dst of size siz. At most siz-1 characters
// will be copied. Always NUL terminates (unless siz == 0).
// Returns strlen(src); if retval >= siz, truncation occurred.
size_t
strlcpy(char *dst, const char *src, size_t siz);
而使用 strlcpy,就不需要我们去手动负责 /0 了,仅需要把 sizeof(dst) 告之 strlcpy 即可:
strlcpy(path, src, sizeof(path));
len = strlen(path);
if ( len >= sizeof(path) )
printf("src is truncated.");
并且 strlcpy 传回的是 strlen(str),因此我们也很方便的可以判断数据是否被截断。
#include<stdio.h>
#include<string.h>
int tar, ans, par[10], part[10];
char num[10];
bool err, rej;
int fun(char *now)
{
int val = 0,i;
for(i = 0; i < strlen(now); i ++)
{
val *= 10;
val += now[i] - '0';
}
return val;
}
void print(char *num)
{
printf("%d",ans);
for(int i = 1; part[i] != 0; i ++)
{
char now[7];
strncpy(now, num, part[i]);
now[part[i]] = 0;
num = num + part[i];
printf(" %s",now);
}
printf("\n");
}
void dfs(int sum, char *num, int dep)
{
if(num[0] == 0)
{
err = false;
if(sum > ans)
{
ans = sum;
rej = false;
for(int i = 1; i < dep; i ++)
part[i] = par[i];
part[dep] = 0;
}
else if(sum == ans)
rej = true;
return;
}
for(int i = 1; i <= strlen(num); i ++)
{
char now[7], next[7];
strncpy(now, num, i);
strcpy(next, num + i);
now[i] = 0;
int val = fun(now);
if(sum + val > tar) continue;
par[dep] = i;
dfs(sum + val, next, dep + 1);
}
}
int main()
{
while(scanf("%d %s",&tar,num)!=EOF && (tar || (num[0]-'0') ))
{
err = true;
rej = false;
ans = 0;
dfs(0, num, 1);
if(err) printf("error\n");
else if(rej) printf("rejected\n");
else print(num);
}
return 0;
}