Dec 3, 2009 at 8:27am UTC
This code is inside the constructor to a class. When I run my program it crashes and this is the output before it does so:
no problem here
or here
right here
this 0 0
0 output here
j: 0 k: 0 save[j][k]: 0
this 0 1
0 output here
j: 0 k: 1 save[j][k]: 17
at end of while loop
no problem here
or here
right here
this 0 0
0 output here
>Exit code: -1073741819
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
//seed generator for latter use
srand(std::time(0));
properTime = 0;
rows = 1;
obstacles = new unsigned int *[rows];
unsigned int i = 0;
//memory allocated for elements of each column.
for (unsigned int i = 0 ; i < rows ; i++)
obstacles[i] = new unsigned int [COLUMNS];
unsigned int timeOfCaging = whenCaged();
while (properTime < SECONDS_WORKED)
{
std::cout<<"no problem here" <<std::endl;
timeOfCaging = Drib::whenCaged();
obstacles[i][0] = timeOfCaging;
obstacles[i][1] = Drib::GetRandomNumber(0, TREE_HEIGHT-1);
std::cout<<"or here" <<std::endl;
//resize
/
save = new unsigned int *[rows++];//increases the rows by 1
std::cout<<"right here" <<std::endl;
for (unsigned int j = 0; j < rows-1; j++){
for (unsigned int k = 0; k < COLUMNS; k++){//columns is equal to 2
std::cout<<"this " <<j<<" " <<k<<std::endl;
std::cout<<obstacles[0][0]<<" output here" <<std::endl;
save[j][k] = obstacles[j][k];
std::cout<<"j: " <<j<<" k: " <<k<<" save[j][k]: " <<save[j][k]<<std::endl;
}
}
//rows++;
delete [] obstacles;
obstacles = save;
properTime += whenCaged();
i++;
std::cout<<"at end of while loop" <<std::endl;
}
std::cout<<"exit here" <<std::endl;
Last edited on Dec 3, 2009 at 8:28am UTC
Dec 3, 2009 at 11:26am UTC
Does this code allocate a larger array?
save = new unsigned int *[rows++];//increases the rows by 1
Dec 3, 2009 at 4:27pm UTC
I'm not too sure how large it will get, but it crashes on the third itteration of the while loop, so that means that the array is only of length 3
Dec 3, 2009 at 5:14pm UTC
The point is, you're using post increment rather than pre increment.
The space for the new array is no larger than the space for the old one. Then you index off the end, corrupting the heap.
You should be using:
save = new unsigned int *[++ rows];//increases the rows by 1