In a book there is an example about static/non-static objects.
char buf[MAX];
long count=0;
int i=0;
while(i++<=MAX)
if(buf[i]=='\0') {
buf[i]='*';
++count;
}
assert(count<=i);
It is said that sometimes the code will write past the end of the buf array into count and make the assertion to fail. And then tells about declaring count as static and solve the problem (note: the author gives this as a bad solution example) Anyway, apart from being a bad example, I cannot figure out how the problem happens, and how it is solved as declaring count as static.
The example counts on a specific layout of the variables in memory, namely that
countcomes just afterbuf. By makingcountstatic, it gets placed in a different part of memory and something else gets clobbered instead. The problem didn’t go away, the symptoms just changed.