常用字符串操作函数
strcat, 连接字符串
strcpy, 拷贝字符串
以上两个函数经常会出现stack overflow问题,长度问题导致的等。
以下两个是相对安全一点的。
strncat
strncpy
但是,我个人常用的是snprintf函数,这个函数保证以NUL结尾的。所以从来不参考以上的函数。
发现新大陆
重温privoxy源码,发现了下面的函数
strlcpy
strlcat
只不过这两个函数并不是ANSI C标准库的一部分。
源于BSD的代码,既然有了这么好的实现为什么不加上呢? 很多平台下已经加上了这两个函数包括Linux。
使用样例
len = strlcpy(path, homedir, sizeof(path);
if (len >= sizeof(path))
return (ENAMETOOLONG);
len = strlcat(path, "/" , sizeof(path);
if (len >= sizeof(path))
return (ENAMETOOLONG);
len = strlcat(path, ".foorc", sizeof(path));
if (len >= sizeof(path))
return (ENAMETOOLONG);
strlcat, strlcpy头文件问题
鉴于ANSI C并不包含相应的头文件,所有要从网上找到也并不容易,我这里有个鄙陋的实现。
源码来自privoxy代理程序
size_t privoxy_strlcpy(char *destination, const char *source, const size_t size)
{
if (0 < size)
{
snprintf(destination, size, "%s", source);
/*
* Platforms that lack strlcpy() also tend to have
* a broken snprintf implementation that doesn't
* guarantee nul termination.
*
* XXX: the configure script should detect and reject those.
*/
destination[size-1] = '\0';
}
return strlen(source);
}
参考链接
https://www.sudo.ws/todd/papers/strlcpy.html
http://blog.csdn.net/kailan818/article/details/6731772