Home > Blockchain >  Setting pointer to NULL fixes project
Setting pointer to NULL fixes project

Time:09-17

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.

CodePudding user response:

  1. In a constructor, you don't need to check for "previous" state of the variables, just set it to what you need, unconditionally.

  2. Are you sure you want a pointer to Apple and not that object itself? If you had in your class

    Apple apple;

it would be default-constructed for you, and you won't need to explicitly delete it (that you may forget, leaking memory).

CodePudding user response:

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.

  • Related