I haven’t used C++ in quite a while and I seem to be making what I’m sure is a very stupid mistake. Could someone tell me why
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
double* atoms;
atoms = (double*)malloc(10 * 3*sizeof(double));
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
atoms[i*10 + j] = 2.0;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
cout << atoms[i*10 + j] << endl;
}
cout << endl;
}
free(atoms);
return 0;
}
is printing
2
2
2
2
2
2
2
2
2
6.94528e-310
6.94528e-310
0
0
4.24399e-314
4.24399e-314
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
instead of all 2’s? Thanks
malloc(10 * 3*sizeof(double))allocates enough memory for 30 doubles.The loop:
accesses well past the last allocated element (which would be
atoms[29]). For example, wheni == 3andj == 0you’re accessingatoms[30]. Any accesses wheni >= 3are out of bounds.