开发者

Objective C(++) Insanity -- simple assignement to a single float variable results in {{{CRAZY}}} values in another variable

memberA is defined in the header of ClassA.

memberB is defined in the header of ClassB.

ClassB is a subclass of ClassA

Inside an instance of ClassB, setting memberA via simple assignment:

memberA = 0.05

...also changes memberB, but to a crazy number -- 1028443341. Additionally, assigning 0.05 to memberA results in memberA showing up in the debugger as 5.33083531e-38.

Both variables are floats, neither is a pointer. I'm almost certianly making some noob mistake, but I don't have any clue what it might be. What sort of screw-up might make it so assigning a value to one variable results in crazy values appearing in two variables?

********************* Edit **********************

I narrowed the problem down to some "trickiness" I'd done in order to get C++ member variables:

Thanks for all the thoughts folks. It's dangerous letting a noob like me at this low-level language stuff! Here's where the problem was:

@interface LoopyPulser : NSObject{

 float _pulseRate;
 UInt32 tickInterval;
 UInt32 step;
 InMemoryAudioFile * audioFilePlayer;
 #ifdef __cplusplus
  ADSR* env;
  StkFrames* audioFrames;
 # e开发者_运维技巧ndif
 Pattern * pattern;
 float loopLengthRatio;
 float volume;
}

I read about this #ifdef __cplusplus business somewhere else on SO, as a way to have C++ imports in header files which are then imported by Obj-C files. Seems to me now that this is a terrible idea, and most likely the cause of my crazy bug. If I remove the member vars inside the #ifdef __cplusplus, the insanity goes away.

So what's the best way to have C++ member variables in Obj-C++? Can I use ids maybe?


Sounds like memberA and memberB are floating point members of a class that is experiencing random memory corruption due to your program being written with some errors.

(1) Reference counting error (if you're not using GC) could result in the retain count hitting zero and an object being disposed of, that you are still holding your own reference to. Then the memory can be re-used and cause this interesting result.

(2) Some other pointer math, faulty indirection, or other C programming or ObjectiveC type mistakes (shoot self in foot).

Don't assume these are the only two things that are broken. How about putting the following into your code:

// in your class declaration 1
int Magic1;
float MemberB;
int Magic2;
// same thing in class declaration 2:
int Magic1;
float MemberA;
int Magic2;


// somewhere else like your setup code for each of the two classes:
Magic1 = MAGIC_1;
Magic2 = MAGIC_2;

// somewhere else where the bug occurs
if (Magic1 != MAGIC_1) || (Magic2 != MAGIC_2) { ... do something helpful like NSLog(...)  ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜