如何正确进行memcpy而不会出现溢出问题

问题描述 投票:0回答:1

在遗留代码中,我在强化审计中遇到缓冲区溢出错误。
让我在这里解释一下这个问题:
我有一个函数,比如说

foo(size_t len, unsigned char **buf)
,在这个
foo
中,我是 memcopying buf 中的字符串变量,如下所示。

std::string temp = "abcd" + somefunct_returning_string(); //so the string is variable length

memcpy(*buf, temp, temp.length()); 

实际上,

temp.length()
始终是
< len
(这是buf分配的大小)。但强化会带来潜在的风险。

我该如何解决这个问题?

c++ memcpy buffer-overflow
1个回答
0
投票

尝试使用 std::string::data() 函数来访问字符串。

memcpy(*buf, temp.data(), temp.length());
© www.soinside.com 2019 - 2024. All rights reserved.