2

Is it an indefinite behavior from an uninitialized variable?

 3 years ago
source link: https://www.codesd.com/item/is-it-an-indefinite-behavior-from-an-uninitialized-variable.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Is it an indefinite behavior from an uninitialized variable?

advertisements

Is using an uninitialized variable as the src for memcpy undefined behaviour in C?

void foo(int *to)
{
  int from;
  memcpy(to, &from, sizeof(from));
}


The C committee proposed response to defect report 451: instability of uninitialized automatic variables is:

The answer to question 3 is that library functions will exhibit undefined behavior when used on indeterminate values.

The question in the defect had sought an exemption for memcpy and fwrite if this was indeed the case saying:

[...] The fact that one wants to be able to copy uninitialized padding bytes in structs using memcpy without undefined behavior is the reason that using the value of an uninitialized object is not undefined behavior. This seems to suggest that an fwrite of a struct with uninitialized padding bytes should not exhibit undefined behavior.

This part of the propose response seems to be aimed at that concern over uninitialized padding:

The committee also notes that padding bytes within structures are possibly a distinct form of "wobbly" representation.

We can see form defect report 338: C99 seems to exclude indeterminate value from being an uninitialized register this is somewhat of a change from past expectations. It says amongst other things:

[...] I believe the intent of excluding type unsigned char from having trap representations was to allow it to be used to copy (via memcpy) arbitrary memory, in the case that memory might contain trap representations for some types.[...]

The blog post Reading indeterminate contents might as well be undefined covers the evolution of reading indeterminate values in C well and make some more sense of the changes I mention above.

It is worth noting this differs from C++ where reading an indeterminate value from a narrow unsigned char is not undefined behavior and defect report 240 notes this difference:

The C committee is dealing with a similar issue in their DR338. According to this analysis, they plan to take almost the opposite approach to the one described above by augmenting the description of their version of the lvalue-to-rvalue conversion. The CWG did not consider that access to an unsigned char might still trap if it is allocated in a register and needs to reevaluate the proposed resolution in that light. See also issue 129.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK