Unsolved Program Crashes at Runtime, but doesn't crash when being stepped through.
-
Hi there, I've been developing a QT application for the first time over the last couple of days and it's being going well. Today I added a regular C++ function to my program and tested it out.
- If I remove the call to this function then the program will run perfectly with no crashes (but no new function of course)
- If I place the call the function back into the program, then my program will crash at Runtime (When I click a button to start my program).
- However, if I leave the function in the program, and place a breakpoint at the start of the function, I can step through my entire program until it finishes without a single crash.
Has anyone experience something like this before?
Here is the function that's causing the issue (I believe I'm getting an access violation error):
void SokoGenerator::rotatePattern(twoDVector *pattern, int rotation){ twoDVector tempPattern = *pattern; if(rotation == 1){ //Rotate by 90 - reverse each row for(int i = 0; i < tempPattern[i].size(); i++){ std::reverse(tempPattern[i].begin(), tempPattern[i].end()); } *pattern = tempPattern; } else if(rotation == 2){ //Rotate by 180 - reverse each row, then each column for(int i = 0; i < tempPattern[i].size(); i++){ std::reverse(tempPattern[i].begin(), tempPattern[i].end()); } std::reverse(tempPattern.begin(), tempPattern.end()); *pattern = tempPattern; } else if(rotation == 3){ //Rotate by 270 - reverse each column std::reverse(tempPattern.begin(), tempPattern.end()); *pattern = tempPattern; } }
Quick background - 'twoDVector' is a type I created which is declared as:
typedef <vector <vector<char> > twoDVector;
Thanks, RBrNx277
-
Hello,
You are (probably) going out of bounds, that's why your program is crashing.for(int i = 0; i < tempPattern[i].size(); i++)
Don't you mean?
for(int i = 0; i < tempPattern.size(); i++)
I'd like also to point out, that if you're doing:
twoDVector tempPattern = *pattern; // ... Some code *pattern = tempPattern;
Then it's best to use references and not pointers, also use switch and enums instead of if-else-if-else. Like this:
enum Rotation { Rotate90Degrees, Rotate180Degrees, Rotate270Degrees }; void SokoGenerator::rotatePattern(twoDVector & pattern, Rotation rotationFlag) { switch (rotationFlag) { case Rotate90Degrees: for(qint32 i = 0, size = pattern.size(); i < size; i++) //< Good idea to use a temporary for the size, no need to call the method every iteration std::reverse(pattern[i].begin(), pattern[i].end()); break; case Rotate180Degrees: // ... More code break; default: //< Handle incorrect flags here! cerr << "Error incorrect flag passed to SokoGenerator::rotatePattern"; } }
Looks a bit simpler without the pointer dereferencing, doesn't it?
Kind regards.