Memory leak(?) causing crash
I'd recommend providing more information in your post. You can simplify your code down to something that works, then add things back slowly until it breaks. You can step through with a debugger until it crashes, then check your values that caused the crash. Posting information learned from either of those would be quite useful. You can also post more of your code and hope someone is willing to sift through it.
1. Your calculations for idx2 and idx3 are incorrect.
Might I suggest the following replacement lines of code
2. Use initialiser lists more, as per the following:
3. Your "sparks=0" in the destructor is pointless as after that line, the object no longer exists. The other zeroing-outs are pointless as well, as is the 'if'. The following would be better:
4. Better yet is using a std::vector instead of manual allocation. Observe:
5. Or even better yet if you store objects instead of pointers:
Might I suggest the following replacement lines of code
int idx2 = ((rand() & 1) + 1 + idx) % 3; int idx3 = 3 - idx1 - idx2;
2. Use initialiser lists more, as per the following:
Sparkle::Sparkle(Vector2D location, float radius, int numParticles) : location(location), radius(radius), numParticles(numParticles) { sparks = new Spark*[numParticles]; for (int i=0; i<numParticles; i++) { sparks = new Spark(); }}
This also negates any necessity to use "this->".[cool]3. Your "sparks=0" in the destructor is pointless as after that line, the object no longer exists. The other zeroing-outs are pointless as well, as is the 'if'. The following would be better:
Sparkle::~Sparkle() { for (int i=0; i<numParticles; i++) { delete sparks; } delete [] sparks;}
4. Better yet is using a std::vector instead of manual allocation. Observe:
Sparkle::Sparkle(Vector2D location, float radius, int numParticles) : location(location), radius(radius), numParticles(numParticles), sparks(numParticles){ for (int i=0; i<numParticles; i++) { sparks = new Spark(); }}Sparkle::~Sparkle() { for (int i=0; i<numParticles; i++) { delete sparks; }}
Done![cool][cool]5. Or even better yet if you store objects instead of pointers:
Sparkle::Sparkle(Vector2D location, float radius, int numParticles) : location(location), radius(radius), numParticles(numParticles), sparks(numParticles){}
No destructor required![cool][cool][cool]
Still crashing ?
I didn't see any problem with your memory allocation. It is possible that the problem isn't in this code (although the symptoms appear here). You might do something bad to the memory elsewhere.
Memory leak alone doesn't cause crash.
Look for double deleted pointers or incorrect use of new/new[] vs delete/delete[].
Cheers !
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement