title: How is the value of this variable changing in my C code?
body: <p>I have come across a very odd problem in C that I have never encountered before. I have narrowed it down to the following very simple snippet.</p>
  
  <p>The variables are global and of type:</p>
  
  <pre><code>    int cpd;
      int nPart;
  </code></pre>
  
  <p>And here is the relevant code snippet which I gradually stripped down to the very minimum needed to produce the issue:</p>
  
  <pre><code>    printf("\ncpd1: %d\n",cpd);
  
      int p;
      for(p=1;p&lt;=nPart;p++)
      {
          printf("\ncpd2: %d\n",cpd); exit(0);
      }
  </code></pre>
  
  <p>...The output I get is this:</p>
  
  <pre><code>cpd1: 17
  
  cpd2: 0
  </code></pre>
  
  <p>How on earth is this possible?!
  cpd has NOT been reassigned, NO functions have been called... yet it changed?
  HOW?!?!</p>
  
  <p>This has been driving me slowly insane for quite some time now...
  ... so any ideas?</p>
  
  <p>thanks for your time,
  Ben.</p>
  
  <p>EDIT: and when I remove -02 from the makefile arguments to gcc, BOTH the print statements tell me that cpd = 0!</p>
  
  <p>EDIT: Okay, I just found that a variable that is declared globally once, initialised as 4.0, and then never modified is now apparently 1.51086e-311   ... Something is very wrong somewhere...</p>
  
  <p>EDIT: SOLVED!: I had an array of size 1000 that needed to be over 4000, and trying to write to this was corrupting the memory around it. Thing is, this array is NOT accessed anywhere near those print statements, it <em>is</em> accessed in the same function however, much earlier on (large function!). The weird discrepancy between print statements must be some weird artifact of using -O2, as without -O2, both prints of cpd print the corrupted version. Thank you everyone, I wouldnt have worked this out without your help!</p>