I ran into a very strange problem in C that I had never encountered before. I narrowed it down to the next very simple fragment.
Variables are global and have the type:
int cpd; int nPart;
And here is the corresponding piece of code, which I gradually divided to the minimum necessary to create the problem:
printf("\ncpd1: %d\n",cpd); int p; for(p=1;p<=nPart;p++) { printf("\ncpd2: %d\n",cpd); exit(0); }
... I get the output:
cpd1: 17 cpd2: 0
How is this possible ?! cpd was not reassigned, NO functions were called ... but has this changed? AS?!?!
It has quieted me for quite some time ... ... so any ideas?
Thanks for your time, Ben.
EDIT: and when I remove -02 from the makefile arguments in gcc, BOTH print sentences tell me cpd = 0!
EDIT: Well, I just found that a variable declared globally once, initialized as 4.0, and then never been changed, now looks like 1.51086e-311 ... Something very wrong somewhere ...
EDIT: SOLVED !: I had an array of size 1000, which should have been larger than 4000, and trying to write this distorted the memory around it. The fact is that this array is NOT accessible anywhere next to these print operations, but it is available in the same function, but much earlier (a big function!). The strange mismatch between print statements should be some kind of strange artifact of using -O2, since without -O2 both cpd prints print a damaged version. Thanks to everyone, I would not have managed this without your help!
source share