Search code examples
cvariablescompiler-errorscompiler-constructiongarbage

Compiler contribution in assigning garbage values in c


Can we say that when garbage values are assigned to variables in C, they are related to the programs that are executed on the compiler previously ? Like some values of previous programs retained by the compiler and then are assigned in the form of garbage to the unassigned variables ? Like for example - if in a previous program we get a value 78. So in any following program is it possible that in any assigned variable we get to see that value or any other values retrieved from any previous programs ?


Solution

  • While anything is possible, since the language spec doesn't prohibit it, it's extremely unlikely.

    For security reasons, operating systems normally ensure that a new process doesn't receive any memory contents from previous processes. So each compiler process starts with fresh memory.

    And it would quite perverse for the compiler itself to save the data between invocations. There's no reason to do so, and it would require extra work to save and retrieve it.

    When a variable is not initialized, there's no code that's intentionally putting "garbage" into it (unless you're using software like valgrind that's designed to detect uses of uninitialized data). A memory address is assigned to it, and it just uses whatever happens to be in that memory. In the case of variables on the stack, this might be data left over from the stack frame of a previous function call, or temporaries used in earlier calculations, etc.

    But none of this will likely come from the compiler itself.