I got the following warning because of the variable a
:
C6385: Reading invalid data from 'z': the readable size is 'a*4' bytes, but '12' bytes may be read
In addition, the return
line is marked green in my IDE. How should I fix this?
int function(int a)
{
int* z = new int[a];
return z[2];
}
I'm using Microsoft Visual Studio 16.6.2.
I don't know why you use dynamic memory allocation. 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. 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;
will actually do the job. No warning anymore. Thanks for help anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.