如何避免strcpy_s缓冲区太小

Har*_*Boy 0 c c++ char

我需要复制std::string data到char数组中。我的字符串的长度是可变的,但是我的char数组的长度是固定的。

const int SIZE = 5;

char name[SIZE];
std::string data = "1234567890";

strcpy_s(name, 5, data.c_str()); //causes a buffer is too small assertion
strcpy_s(name, 11, data.c_str());//copies fine (length of data plus null)
strcpy_s(name, sizeof(data), data.c_str()); // copies fine
Run Code Online (Sandbox Code Playgroud)

每次如何安全地仅复制阵列的长度?没有获取断言,也没有导致缓冲区溢出。

我应该每次都这样吗?

std::string toCopy = data.substr(0,SIZE-1);
strcpy_s(name, toCopy.c_str());
Run Code Online (Sandbox Code Playgroud)

The*_*ish 5

strncpy_s_TRUNCATE

例如:

strncpy_s(name, data.c_str(), _TRUNCATE);
Run Code Online (Sandbox Code Playgroud)

将尽可能多地复制以填充name缓冲区,同时仍然考虑空终止(与传统的strncpy不同)。