Reputation: 770
in my objective-c program (or, maybe, in debugging utility) I get a bizarre behavior.
I defined, but not allocated or initialized 4 instances of some class (let it be "Rectangle"):
Rectangle *left, *right, *bottom, *upper;
Right after this line, I expect that for all of my four objects will be null pointers (debugging in Xcode), but for one of them (concretely "upper") exist point to some memory location, and his properties is initialized with random values.
Does it normal behavior? If so, please explain me why. (I am a bit new to objective-c programming)
Upvotes: 1
Views: 123
Reputation: 361
Use ARC, its amazing as memory management isn't handled by you anymore!
Upvotes: 0
Reputation: 3045
You should do this...
Rectangle *left = nil;
Rectangle *right = nil;
Rectangle *bottom = nil;
Rectangle *upper = nil;
which is the same as
Rectangle *left = nil, *right = nil, *bottom = nil, *upper = nil;
Upvotes: 0
Reputation: 43452
Objective C does not (in general) guarantee that stack values are zeroed. It does guarantee that all ivars in an object are zeroed. Also, under ARC it does zero stack vars that it knows are objects. So the behavior you are seeing is correct assuming you are not using ARC.
In general, even if you are in an environment that zeros the value you should explicitly zero it in case your code gets reused somewhere else. If there is a constraint your code needs to work you should either satisfy it, test for it at runtime, or test for it at compile time (assert()
).
As for why this is the case, it is that way because C behaves that way, and C traditionally has done it because it is bare metals and prefers to let the compiler have a lot of liberty in order to do performance optimizations. Objective C only differs in places where it needs to in order to support its own (supplemental) functionality.
Upvotes: 5
Reputation: 16938
Pro-tip: Never assume anything. It is good practice to initialize all your variables to a known value; in this case, nil
.
If you are coming from another high-level language that does initialize variables for you, well... this isn't that language. :-)
Upvotes: 2