On a semi-large project (~5000+ lines of code)...
I have a class with a pointer as one of its fields. The pointer was declared but not initialized:
Apple *apple;
In the class's constructor, I initialized the pointer if it was NULL
:
if (apple == NULL) {
apple = new Apple();
}
Further down in the project's code, I did:
apple->color = "red";
The program worked fine for months, until today it gave me a EXC_BAD_ACCESS
error, because the apple
pointer was not explicitly initialized to NULL
and started out with some garbage value - so the NULL
check failed, and dereferencing it gave a EXC_BAD_ACCESS
.
So my question is - how did the program work fine for months? Was the pointer set to NULL
previously by pure luck?
Note: I made no changes to the code here, only changes elsewhere in the project that didn't touch this/seem irrelevant.
It's hard to tell decisively, but probably yes, the program worked by sheer luck.
If you don't explicitly initialize a pointer you can't assume anything about it, and TBH, it's not surprising that the program started crashing, but that it worked up until now.