如何防止 strncpy_s 在调试版本中填充目标缓冲区? [英] How can I prevent strncpy_s from padding destination buffer in debug build?
问题描述
我维护了一段相当大的遗留代码,这些代码仍然大量使用 strncpy
.我现在已经开始将 strncpy
的用法替换为其安全对应物 strncpy_s
的过程.我注意到 strncpy_s
正在用 -2 值填充目标缓冲区 - 但仅在调试版本中!在发布版本中不发生填充.
例如:
字符缓冲区[3];//缓冲区变为 00000000 00000000 00000000memset(buffer, 0, sizeof(buffer));//缓冲区变为 01100001 00000000 11111110//97 ('a') 0 -2strncpy_s(buffer, sizeof(buffer), "a", _TRUNCATE);//我是-2int i = 缓冲区[2];
MSDN 文档 没有提到这种填充行为,并且在我的情况确实是我不想要的东西,因为我的遗留代码依赖于这样一个事实,即缓冲区的归零部分保持归零并且在字符串复制期间不会被覆盖.
有什么方法可以防止 strncpy_s
在调试版本中填充目标字符串?
请注意,我已使用 Visual Studio 2010 和 Visual Studio 2013 对此进行了测试.
strcpy_s()
只会在调试模式下用 'FE'
填充缓冲区.>
您可以通过调用 _CrtSetDebugFillThreshold(0)
来明确关闭此功能I maintain a fairly large piece of legacy code that still uses strncpy
a lot. I have now started the process of replacing the usage of strncpy
with its safe counterpart strncpy_s
. I noticed that strncpy_s
is padding the destination buffer with -2 values - but only in debug builds! In release builds no padding occurs.
For instance:
char buffer[3];
// buffer becomes 00000000 00000000 00000000
memset(buffer, 0, sizeof(buffer));
// buffer becomes 01100001 00000000 11111110
// 97 ('a') 0 -2
strncpy_s(buffer, sizeof(buffer), "a", _TRUNCATE);
// i is -2
int i = buffer[2];
The MSDN docs do not mention this padding behaviour, and in my case it's really something I don't want because my legacy code relies on the fact that the zeroed parts of the buffer remain zeroed and are not overwritten during string copying.
Is there a way how I can prevent strncpy_s
from padding the destination string in debug builds?
Note that I have tested this with both Visual Studio 2010 and Visual Studio 2013.
strcpy_s()
will fill in the buffer with 'FE'
in debug mode only.
You can turn this off explicitly by calling _CrtSetDebugFillThreshold(0)
这篇关于如何防止 strncpy_s 在调试版本中填充目标缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!