Is it undefined behaviour to memcpy from an uninitialized variable?

前端 未结 3 1240
轻奢々
轻奢々 2020-12-20 11:24

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

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


        
3条回答
  •  礼貌的吻别
    2020-12-20 11:49

    This is defined behaviour with respect to the action of copying, except if int has a trap representation in your system. Memory was allocated on the stack when int from was defined. The contents of this int is whatever happened to be on that location in the stack at that moment. Therefore the end result, the value of the int that is being copied to to is not defined (indeterminate).

    Other answers have quotes from the C standard that undefined behaviour occurs when the value of an uninitialised variable is "used". Which obviously doesn't apply if you don't use the value. There is another mention in the C11 standard undefined behaviour while copying/assigning uninitialised variables :

    6.3.2.1p2

    If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

    This also doesn't affect your code because the address of from is taken when you call memcpy

    Another relevant part of the C11 standard is 6.2.6.1

    Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined) Such a representation is called a trap representation.

    Some very old processors could have a trap representation for an int either software-visible parity bits or "negative zero" in non-twos-complement architectures. x86 processors for example don't have trap representations for int.

提交回复
热议问题