0

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 ?

  • Short answer: no. Longer answer: no, of course not. `char txt[1000]; /*garbage: may be the lyrics of the national anthem of Spain*/` – pmg Aug 13 '20 at 18:46
  • Welcome to SO! Maybe yes, maybe no, but you can't count on anything. Can you provide context on why you need to know this? Also, are you sure the _compiler_ is assigning these values? – ggorlen Aug 13 '20 at 18:46
  • If a variable is not initialized as part of its declaration, or before first use at run-time, then it will contain whatever happens to occupy the space assigned to it. Good idea to initialize before using, always. – ryyker Aug 13 '20 at 18:47
  • This is effectively a duplicate of https://stackoverflow.com/questions/1422729/how-does-an-uninitiliazed-variable-get-a-garbage-value. – mbauman Aug 14 '20 at 16:53

1 Answers1

3

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612