为什么不函数strncpy空终止? [英] Why does strncpy not null terminate?

查看:438
本文介绍了为什么不函数strncpy空终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数strncpy()理应从缓冲区溢出保护。但如果prevents没有空终止溢出,在所有的情形产生后续的字符串操作会溢出。因此,为了防止这一点,我觉得自己做的:

strncpy() supposedly protects from buffer overflows. But if it prevents an overflow without null terminating, in all likelyhood a subsequent string operation is going to overflow. So to protect against this I find myself doing:

strncpy( dest, src, LEN );
dest[LEN - 1] = '\0';


男人函数strncpy 给出:

该函数strncpy()功能类似,不同之处在于不超过n个字节的src复制。因此,如果为src的前n个字节之间没有空字节,结果不会是空终止的。

The strncpy() function is similar, except that not more than n bytes of src are copied. Thus, if there is no null byte among the first n bytes of src, the result will not be null-terminated.

如果没有空终止的东西貌似无辜的,如:

Without null terminating something seemingly innocent like:

   printf( "FOO: %s\n", dest );

...可能崩溃。

...could crash.

有没有更好的,更安全的替代函数strncpy()

Are there better, safer alternatives to strncpy()?

推荐答案

函数strncpy 不打算被用来作为一个更安全的的strcpy ,它应该被用来在另一中间插入一个字符串。

strncpy is not intended to be used as a safer strcpy, it is supposed to be used to insert one string in the middle of another.

所有这些安全的字符串处理函数,如的snprintf vsnprintf 是已经被后来添加的修补程序标准以减轻缓冲区溢出攻击等。

All those "safe" string handling functions such as snprintf and vsnprintf are fixes that have been added in later standards to mitigate buffer overflow exploits etc.

维基百科提到 strncat函数作为替代书写你自己的安全函数strncpy

Wikipedia mentions strncat as an alternative to writing your own safe strncpy:

*dst = '\0'; strncat(dst, src, LEN);

修改

我错过了strncat函数超过LEN个字符时,空终止字符串,如果是长于或等于LEN字符的。

I missed that strncat exceeds LEN characters when null terminating the string if it is longer or equal to LEN char's.

反正使用strncat函数代替任何自产溶液如memcpy的点(...,strlen的(...))/不管是strncat函数的执行可能是目标/平台在库优化。

Anyway, the point of using strncat instead of any homegrown solution such as memcpy(..., strlen(...))/whatever is that the implementation of strncat might be target/platform optimized in the library.

当然,你需要检查DST至少持有nullchar,所以正确的使用strncat函数将是这样的:

Of course you need to check that dst holds at least the nullchar, so the correct use of strncat would be something like:

if(LEN) { *dst = '\0'; strncat(dst, src, LEN-1); }

我也admitt了函数strncpy不是复制子到另一个字符串中非常有用,如果src超过n字符的短,目标字符串将被截断。

I also admitt that strncpy is not very useful for copying a substring into another string, if the src is shorter than n char's, the destination string will be truncated.

这篇关于为什么不函数strncpy空终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆