Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

c - Is it undefined behaviour to memcpy from an uninitialized variable?

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...