Search code examples
cvolatileundefined-behavior

Can an uninitialized automatic volatile variable in C be safely read?


In C, can I access an automatic volatile variable without having to initialize it first, or does it always result in undefined behavior?

E.g., in some hardware devices mapped to volatile variables, initializing the variable makes no sense anyway, or might even be forbidden.


Solution

  • An automatic variable is generally on the call stack (but this is implementation specific), so it generally won't be some hardware specific "device" (unless your stack pointer is garbage). When that is the case (to be on stack), a variable inherits from the previous content of that stack location. If it is volatile e.g, like in

    void foo(void) {
      volatile int x;
      // here x contains garbage
    }
    

    accessing that x gives some "indeterminate value", and that access is an undefined behavior.

    The C standard does not require any call stack, but most C implementations use the machine call stack.

    Of course, things are different if you have an automatic variable which is a pointer to some volatile data.