[英]Safe string copy in C/C++
I wrote this string copy routine for C strings. 我为C字符串编写了此字符串复制例程。 It is supposed to behave like strlcpy, that is - null terminate the destination if size > 0, and return the length of the source string.
它的行为类似于strlcpy,即-如果size> 0,则null终止目标,并返回源字符串的长度。
However I also want the function to fail if either the source or destination pointer is null, and somehow notify this to the caller. 但是,如果源指针或目标指针为null,则我也希望函数失败,并以某种方式将此通知给调用者。 But I can not think of a very elegant way to do this.
但是我想不出一种非常优雅的方式来做到这一点。 Right now I send two negative values as size to denote that the source or the destination pointer points to null.
现在,我发送两个负值作为大小,以表示源指针或目标指针指向null。 Hence I changed the return type from size_t to a signed integer, and I am not happy with this interface.
因此,我将返回类型从size_t更改为带符号的整数,对此接口我不满意。 What would be a better interface?
什么是更好的界面?
#include <cstddef> // size_t
#include <cstdint> // 32 bit int
const std::int32_t SRC_NULL = -1;
const std::int32_t DST_NULL = -2;
std::int32_t CopyStringn (char *dest, const char *src, std::size_t size) {
const char* temp (src);
if (temp == NULL)
return SRC_NULL;
if (dest == NULL)
return DST_NULL;
while (*temp) {
if (size > 1) {
*dest++ = *temp;
--size;
}
++temp;
}
if (size)
*dest = '\0';
return static_cast<std::int32_t> (temp - src); // Length does not include null
}
在C ++中,可以引发异常。
Magic return values are rarely a good idea. 神奇的返回值很少是一个好主意。 I expect such a function to tell me how many chars would be copied, and that is what should be returned.
我希望有一个函数可以告诉我要复制多少个字符,那就是应该返回的字符。 If src or dest is NULL, you copy 0 characters, return 0.
如果src或dest为NULL,则复制0个字符,并返回0。
Alternatively, you can choose to return either 1/true if everything was copied and properly 0-terminated, and 0/false otherwise. 另外,如果复制了所有内容并正确地以0结尾,则可以选择返回1 / true,否则返回0 / false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.