Search code examples
cvariablesinitializationundefined-behavior

How are garbage values for variables generated in C?


I mean to ask if it follows some specific algorithm and actually are not junk.

In other words, how exactly the "garbage" values be present? Considering not invoking UB, if a garbage value is read, what is the source of that value?


Solution

  • The standard does not mention the term "garbage", it mentions "indeterministic / indeterminate values". The value can be anything.Note

    From the user point of view, if we are unable to get a fix on a certain value (for any variable), then the "expectation" is not matched anytime and the value (if) we get is not of any use, thus terming them as "garbage" is common.

    The most relatable and common observation / implementation is, for an automatic variable left uninitialized, only the storage is allocated, the content of that storage is not touched. So, probably it still contains the last stored value which was put there. Now, that value, probably being a valid one in other (previous) scenario, in present case, does not make any sense, so it is "garbage" in current scenario.

    TL;DR The "garbage" value is not generated, most of the cases, it's just the last stored value in that memory location.


    Note:

    Related quoting from C11, chapter §6.7.9

    If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [....]


    §§ Additional Read:

    This is very closely related to the topic, so adding it as a footnote.

    In case, there exist a variable, which holds indeterministic value and

    • the data type can have trap representation
    • the address of the variable is not taken

    then, trying to read the value actually causes undefined behavior. Be aware.