-2

Is trying to access an uninitialized struct field in C considered undefined behavior?

struct s { int i; };
struct s a;
printf("%d", a.i);
Simo
  • 155
  • 3
  • 12
  • Why might it be different from accessing any other uninitialized memory location? – Govind Parmar May 17 '19 at 20:12
  • As far as I remember, only global variables and static variables are zero initialized. Accessing any other is UB. – DeiDei May 17 '19 at 20:14
  • It depends. Autoimatic storage objects - UB. Static storage objects - no UB – 0___________ May 17 '19 at 22:06
  • This question isn't duplicated at least in "(why) is using an uninitialized variable undefined behavior?". Please look at the first answer by P__J__, compare it with the content where you think there is the duplication and you'll understand that they're two different things. Thankfully, I would like you not to keep closed my question. – Simo May 18 '19 at 09:13
  • @GovindParmar: There are many scenarios where it may be useful to copy a structure of which some but not all members have been written, and some of these situations generalize to the case where different conditions control whether various members get written, and in some cases a function might write none at all. The authors didn't think it necessary to tell compiler writers that such constructs should be supported in the absence of any reason not to support them (such as trapping to avoid possible data leakage) because they expected compiler writers would do so anyway. – supercat May 20 '19 at 14:38

1 Answers1

3

depending on the storage duration of the variable:

struct
{
    int a;
    int b;
}c;

int main()
{

    struct 
    {
        int a;
        int b;
    }e;

    static struct 
    {
        int a;
        int b;
    }s;

    printf("%d", c.a);    // <- correct no UB
    printf("%d", s.a);    // <- correct no UB
    printf("%d", e.a);    // <- UB 
}

structure c & s have a static storage duration and they are always initialized. If programmer does not initialize them explicit way they are zeroed.

structure e has the automatic storage duration and it is not zeroed if not explicitly initialized by the programmer

0___________
  • 60,014
  • 4
  • 34
  • 74