Reputation: 95
So, I'm running a pretty trivial and bare-bones piece of code:
template <typename T>
matrix<T>::matrix(int r, int c, int a)
{
int data2[6*4] = {-1, 12, 23, 34, 45, 56,
11, 22, 33, 44, 55, 66,
21, 32, 43, 54, 65, -1,
31, 42, 53, 64, -1, -1};
mData = new T(6*4);
for(int p=0; p < 6*4; p++){
mData[p] = T(data2[p]);
std::cout << " " << mData[p] << ":";
std::cout << " " << mData[p] << ":" << std::endl; //second time is read
};
for(int p=0; p < 4; p++){
for(int p2=0; p2 < 6; p2++){
if(mData[p2 + p * 6] == 1)std::cout << "FOUND ONE" << std::endl;
}
}
}
int main(){
int i = 6;
matrix<int> b = matrix<int>(i,i, 0);
}
However, at random intervals there are times where a value of a data CHANGES to 1 the second time it's being read. It's never the first time, always the second one. Here you have an example:
-1: -1:
12: 12:
23: 23:
34: 34:
45: 45:
56: 56:
11: 11:
22: 22:
33: 1:
44: 44:
55: 55:
66: 66:
21: 21:
32: 32:
43: 43:
54: 54:
65: 65:
-1: -1:
31: 31:
42: 42:
53: 53:
64: 64:
-1: -1:
-1: -1:
FOUND ONE
Process returned 0 (0x0) execution time : 0.085 s
Press any key to continue.
There is nothing else touching the structure, so I have no idea what could be going on. The number is always saved properly (since the first print is ALWAYS correct), but afterwards it gets corrupted... I got no idea what's going any. Any help?
EDIT:
Solution found, apparently I simply mistook a "[]" for a "()", and despite looking the code over and over never noticed. (it's obvious at hindsight).
Thank you guys.
Upvotes: 1
Views: 64
Reputation: 956
In this line of code:
mData = new T(6*4);
a single instance of T is allocated. Afterwards, the code tries to access that as an array, leading to out of bounds access.
It was probably intended like this:
mData = new T[6*4];
Edit and another tip: In order to reduce error like these and to improve the overall code style, I almost always go for std::vector<T>
instead of T*
when creating arrays of elements. The access pattern rarely changes in code but you don't need to worry about memory management and gain additional bonus methods for almost no costs.
Upvotes: 3