I have the following code in C:
while(tempNode!=NULL) {
int pos = pathNodesCount-1-i;
pathNodes[pos] = tempNode;
//printf("A");
euclidianLength += tempNode->g;
i = i+1;
tempNode = tempNode->parent;
}
if I leave the printf("A") statement commented out, and then compile and run my code, I will get an “application stopped running” Windows error. If I uncomment the printf("A") line, recompile and run, the application will run to its end (printing “A” to the console along the way). Why?
The environment is:
- Windows 7 32bit
- MinGW32 20120426 (and I’ve added MSys 1.0)
- Eclipse Juno for C/CPP
== UPDATE
I’ve tracked my error. I won’t post the exact code as it is too long, but it was a case of creating a char array, and then adding characters at wrong indexes. Something like this:
int otherCrap() {
char* c = malloc(10*sizeof(char));
int i = 0;
for(i = 0; i<13; i++) {
c[i]='a';
}
c[15] = '\0';
printf("A");
printf(c);
return 0;
}
Fixing the thing so that the chars were placed inside the array only at existing indexes, and also ading ‘\0’ char as the last element in the array fixed the issue. However I’m still not clear as to why, when the code was bad, adding a printf(‘A’) before printing the char array didn’t result in a runtime error. From the answers received so far I am to understand that this falls under “undefined behavior”.
Probably because some error in the code causes undefined behavior. Having the code then appear to “work” in the presence of a
printf()is fine.That indexing logic counting backwards looks scary; verify that it’s correct. Print the index before using it, compare to the known size of the
pathNodesarray, if you have one. Beware of the index turning negative or overrunning the capacity ofpathNodes.