如何避免strcpy_s缓冲区太小

时间:2014-10-10 21:53:21

标签: 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

如何每次只安全地复制阵列的长度?没有得到断言而没有导致缓冲区超过运行。

我每次都应该这样做吗?

std::string toCopy = data.substr(0,SIZE-1);
strcpy_s(name, toCopy.c_str());

2 个答案:

答案 0 :(得分:4)

strncpy_s_TRUNCATE

一起使用

例如:

strncpy_s(name, data.c_str(), _TRUNCATE);

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

答案 1 :(得分:2)

以下命令返回ERANGE结果,因为您必须有空间来终止NULL字符。可变数据'拥有10个元素。当strcpy_s达到约束时,' 5'它无法找到终止NULL并返回ERANGE。

strcpy_s(name,5,data.c_str());

Microsoft Documentation

  

strcpy_s函数复制strSource地址中的内容,   包括终止空字符,到#的位置   由strDestination指定。目标字符串必须很大   足以保存源字符串及其终止空字符。   如果源和目标,则strcpy_s的行为未定义   字符串重叠。

替代方法

  string data = "0123456789";
  int SIZE = 5;
  char name[SIZE];

  size_t length = data.copy( name, 0, 5 );
  buffer[ length ] = '\0';