[英]Visual Studio C6385 warning c++
I got the following warning because of the variable a
:由于变量
a
,我收到以下警告:
C6385: Reading invalid data from 'z': the readable size is 'a*4' bytes, but '12' bytes may be read
C6385: 从 'z' 读取无效数据:可读大小为 'a*4' 字节,但可以读取 '12' 字节
In addition, the return
line is marked green in my IDE. How should I fix this?另外,我的IDE的
return
line是绿色的,请问怎么解决?
int function(int a)
{
int* z = new int[a];
return z[2];
}
I'm using Microsoft Visual Studio 16.6.2.我正在使用 Microsoft Visual Studio 16.6.2。
I don't know why you use dynamic memory allocation.我不知道你为什么使用动态 memory 分配。 My recommendation to avoid all the commented problems is to use a vector
我建议避免所有评论的问题是使用向量
int function(int a)
{
std::vector<int> z(std::max(3, a));
return z[2];
}
It will initialize the elements, clean up memory and guarantee the size.它将初始化元素,清理 memory 并保证大小。 An alternative is to throw if the element doesn't exist
另一种方法是在元素不存在时抛出
int function(int a)
{
std::vector<int> z(a);
return z.at(2);
}
or要么
int function(int a)
{
if (a < 3) throw;
std::vector<int> z(a);
return z[2];
}
I figured out: adding if (a < 3) a = 3;
我想通了:添加
if (a < 3) a = 3;
will actually do the job.实际上会完成这项工作。 No warning anymore.
没有警告了。 Thanks for help anyway.
无论如何感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.