问题描述
我收到警告:
warning C4996: 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead.
To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
F:\vuStudio\VC\include\string.h(188) : see declaration of 'strncpy'
我在stackoverflow.com上读到 strcpy
不安全,我应该改用 strncpy
.但是,现在为什么我要警告strncpy不安全?
I read on stackoverflow.com that strcpy
is not safe and I should use strncpy
instead. But now why I am getting warning that strncpy is unsafe ?
我称它为:
strncpy(this->title, title.c_str(), sizeof(this->title));
推荐答案
strncpy
有一些危险的怪癖.
首先,它将复制结束后的目标缓冲区归零,这可能令人惊讶.
First, it zeros the target buffer past the end of the copy, which can be surprising.
第二,如果目标缓冲区中没有足够的空间,则不会不 null终止目标缓冲区.
Second, if there is not enough room in the target buffer, it does not null terminate the target buffer.
第三,如果它被截断,则大部分有效".哪些会阻止错误处理(截断的字符串通常比没用的要糟,但乍一看却不会出现比没用的要糟).
Third, if it truncates, it 'mostly works'. Which discourages error handling (truncated strings are often worse than useless, but do not appear to be worse than useless at first glance).
strncpy_s
需要输入长度(或显式的截断请求),如果没有足够的空间可以终止,则错误(在输出中仅写入长度为零的字符串).输入长度有时不能提供足够的效率(某些更改并非必需),但是即使在错误情况下,它也保证了以空值终止的输出缓冲区(只要它不是nullptr或零长度).我不确定它是否在复制的字符串的末尾归零.
strncpy_s
requires an input length (or explicit truncation request), and errors if there is not enough room to null terminate (writing just a zero length string in the output). The input length is sometimes inefficient to provide (and not required for some of its changes), but it does guarantee a null terminated output buffer (so long as it isn't a nullptr, or zero length) even in error conditions. I am unsure if it zeros past the end of the copied string or not.
此行为防止或减轻了一些常见的字符串代码中的击剑错误.
This behavior prevents or mitigates some common fenceposting errors in string code.
这篇关于为什么将strncpy标记为不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!