Reputation: 617
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.
1.If I remove the call to this function then the program will run perfectly with no crashes (but no new function of course)
2.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).
3.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;
Upvotes: 0
Views: 112
Reputation: 181067
The issue appears to be the condition in your for loops.
for(int i = 0; i < tempPattern[i].size(); i++)
Is going to run a number of times equal to the number of columns of the first row in the vector. If this is not the same as the number of rows in the vector then you are either not going to change enough data or go past the end of the vector which is undefined behavior and can cause an access violation.
If you want to loop through all of the rows in the vector then you need to have
for(int i = 0; i < tempPattern.size(); i++)
Or better yet use a ranged based for loop like
for (auto& e: tempPattern)
std::reverse(e.begin(), e.end());
Upvotes: 2