Is the following code safe, so long as I don't read any elements of the struct's array without setting it with a real value first? Thanks.
const int data_size = 5;
struct Testing
{
int data[data_size];
Testing(const int data[data_size])
{
std::copy(data, data + data_size, this->data);
}
};
int main()
{
int data[data_size];
data[2] = 57;
Testing t(data);
t.data[1] = 93;
}
An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.
Description. The code uses a variable that has not been initialized, leading to unpredictable or unintended results. Extended Description. In some languages such as C and C++, stack variables are not initialized by default.
INTRODUCTION: An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using.
So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.
std::copy
is defined as doing *(result + n) = *(first + n)
for each element in the sequence (§25.3.1). The value given by *(first + n)
is an lvalue expression (§5.3.1/1), in your case referring to an uninitialized value. Since the assignment operator expects a prvalue as it's right operand (this is ill-specified), this will result in lvalue-to-rvalue conversion. Lvalue-to-rvalue conversion on an expression referring to an uninitialized value is undefined behaviour (§4.1):
If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.
So your code has undefined behaviour. The solution is of course to initialize the elements of the array (perhaps with int data[data_size] = {};
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With