Sunday, 15 April 2012

c++ - Making a dumb memory mistake -



c++ - Making a dumb memory mistake -

i haven't used c++ in quite while , seem making i'm sure stupid mistake. tell me why

#include <cstdio> #include <cstdlib> #include <iostream> using namespace std; int main() { double* atoms; atoms = (double*)malloc(10 * 3*sizeof(double)); (int = 0; < 10; i++) { (int j = 0; j < 3; j++) { atoms[i*10 + j] = 2.0; } } (int = 0; < 10; i++) { (int j = 0; j < 3; j++) { cout << atoms[i*10 + j] << endl; } cout << endl; } free(atoms); homecoming 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 2's? thanks

malloc(10 * 3*sizeof(double)) allocates plenty memory 30 doubles.

the loop:

(int = 0; < 10; i++) { (int j = 0; j < 3; j++) { atoms[i*10 + j] = 2.0; } }

accesses past lastly allocated element (which atoms[29]). example, when i == 3 , j == 0 you're accessing atoms[30]. accesses when i >= 3 out of bounds.

c++ memory-leaks

No comments:

Post a Comment