[英]Are there drawbacks to using destsz = sizeof(dst) for strncpy_s()?
I'm working off this: https://en.cppreference.com/w/c/string/byte/strncpy我正在解决这个问题: https : //en.cppreference.com/w/c/string/byte/strncpy
The function header is described as this:函数头描述如下:
errno_t strncpy_s(char *restrict dest, rsize_t destsz, const char *restrict src, rsize_t count);
Is there any significant drawback other than speed, to setting destsz = sizeof(dest)
?除了速度之外,设置destsz = sizeof(dest)
还有什么明显的缺点吗?
If you were to use strncpy_s
like this如果你像这样使用strncpy_s
strncpy_s(dest, sizeof(dest), src, sizeof(src));
This assumes that dest
and src
are expressions representing an array variable, like this.这假设dest
和src
是表示数组变量的表达式,如下所示。
char a[3];
char b[4] = {'a', 'b', 'c', '\0'};
strncpy_s(a, sizeof(a), b, sizeof(b));
If instead, dest
or src
were pointers (for example, char*
), like this.如果相反, dest
或src
是指针(例如, char*
),就像这样。
char* ptr1 = a;
char* ptr2 = b;
strncpy_s(ptr1, sizeof(ptr1), ptr2, sizeof(ptr2));
The code would compile, but the values would be wrong, because sizeof(ptr1)
would be the size of the pointer object, not the size of the array.代码可以编译,但值是错误的,因为sizeof(ptr1)
将是指针对象的大小,而不是数组的大小。 In that case, you would have to provide the size in some other way在这种情况下,您必须以其他方式提供尺寸
So, no direct drawbacks, but using this pattern can be error prone.所以,没有直接的缺点,但使用这种模式可能容易出错。
As suggested by @Alex, when using the Microsoft C Runtime Library, you can directly pass the array expression for the destination without passing the size separately正如@Alex 所建议的,在使用 Microsoft C Runtime Library 时,您可以直接为目标传递数组表达式,而无需单独传递大小
strncpy_s(a, ptr2, sizeof(b));
Then, providing the size is not necessary, and doing so brings nothing except potentially mixing up an array and a pointer.然后,没有必要提供大小,这样做除了可能混淆数组和指针之外没有任何好处。 For example, if one accidentally writes strncpy_s(ptr1, b, sizeof(b))
, the code would not compile, rather than work with the wrong values例如,如果不小心写了strncpy_s(ptr1, b, sizeof(b))
,代码将无法编译,而是使用错误的值
No, in fact the template overloads for strncpy_s
do exactly that when you provide a fixed width array as the destination parameter.不,实际上,当您提供固定宽度数组作为目标参数时, strncpy_s
的模板重载正是这样做的。 However, sizeof(dest)
will not work if dest
is a pointer type, as the size of a pointer is always the size of the native machine word (32 or 64 bit).但是,如果dest
是指针类型,则sizeof(dest)
将不起作用,因为指针的大小始终是本机机器字(32 或 64 位)的大小。 If you have a pointer, you will need to keep track of the allocated size in a second variable.如果您有一个指针,则需要在第二个变量中跟踪分配的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.