Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to copy uninitialized data if it will be unused/set later?

Tags:

c++

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;
}
like image 664
Neil Kirk Avatar asked Mar 05 '13 18:03

Neil Kirk


People also ask

What does it mean when a variable is uninitialized in c++?

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.

What does uninitialized mean in C?

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.

What value does an uninitialized variable contain C?

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.

What is undefined in c++?

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.


1 Answers

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] = {};).

like image 182
Joseph Mansfield Avatar answered Nov 15 '22 08:11

Joseph Mansfield