我有以下代码将一个原始(不以null结尾的)字符串复制到const大小的char数组中,但是当我编译时会收到警告。能否请某人帮助我了解这种代码和平的问题所在?
#include <array>
#include <cstring>
char reason_[20];
template <size_t N>
void CopyStr(char(&out)[N], const std::string_view& in)
{
memcpy(out, in.data(), std::min(in.size(), N));
if (in.size() < N)
out[in.size()] = '\0';
}
int main()
{
CopyStr(reason_, "User request");
}
g ++-8 -O3 -mavx -m64 -std = c ++ 17 -g0 -DNDEBUG -fconcepts -Wall test.cpp
In function ‘void* memcpy(void*, const void*, size_t)’,
inlined from ‘void CopyStr(char (&)[N], const string_view&) [with long unsigned int N = 20]’ at test.cpp:9:11,
inlined from ‘int main()’ at test.cpp:16:12:
/usr/include/x86_64-linux-gnu/bits/string_fortified.h:34:33: warning: ‘void* __builtin_memcpy(void*, const void*, long unsigned int)’ forming offset [14, 20] is out of the bounds [0, 13] [-Warray-bounds]
return __builtin___memcpy_chk (__dest, __src, __len, __bos0 (__dest));
以下是g++-8 --version
g++ (GCC) 8.3.1 20190311 (Red Hat 8.3.1-3)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
没有警告
clang version 9.0.0-2 (tags/RELEASE_900/final)
Target: x86_64-pc-linux-gnu
没有警告
g++ (Ubuntu 9.2.1-9ubuntu2) 9.2.1 20191008
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE