The memory could not be read

I am just starting c++. The problem is that with my function I get the error mesage: The instruction at "0x7c9369da" referenced to memory at "0xffffffff" The memory could not be "read".
I found this topic in the archive: http://www.cplusplus.com/forum/beginner/1930/
but it didn't help me to solve it. I also asked somebody more skilled than me and he didn't know what the problem is.

The code is so far (I wrote in the comments where the problem is):

#include <iostream>
#include <cmath>

using namespace std;

void forcecalculation (int n, double **positions) {
//create array for forces
double **forces;
forces=new double*[n*n];
for (int i=0;i<n*n;i++) {
forces[i]=new double [2]; //the error is in this line, making it comment lets the program run without error message
}

//delete array for forces
for (int i=0;i<n*n;i++) {
delete[] forces[i];
}

delete[] forces;

}

int main()
{
//number of particles on on side
int n=100;
//arrey for coordinates
double **positions;
positions=new double*[n*n];
for (int i=0;i<n*n;i++) {
positions[i]=new double[2];
}

//initial coordinates
for (int i=0;i<n;i++) {
for (int j=0;j<n;j++) {
positions[j+i*n][1]=j;
positions[j+i*n][2]=i;
}
}
//movement
forcecalculation (n,positions);


//delete array for positions
for (int i=0;i<n*n;i++) {
delete[] positions[i];
}
delete[] positions;
return 0;
}


The exactly same thing that I do in the main function doesn't seem to work in the void function.

Edit: If this problem is posted in the wrong forum please tell me.
Last edited on
Indexing problems abound.

You allocate a 1000 by 2 array, but use the wrong indices when filling it in.
1
2
3
4
5
6
	for (int i=0;i<n;i++) {
		for (int j=0;j<n;j++) {
			positions[j+i*n][1]=j;
			positions[j+i*n][2]=i;
		}
	}

Should be:
1
2
3
4
5
6
	for (int i=0;i<n;i++) {
		for (int j=0;j<n;j++) {
			positions[j+i*n][0]=j;
			positions[j+i*n][1]=i;
		}
	}
Thank you, that solved the problem. I still wonder why this works when I make the line above comment.
You're overwriting parts of the heap and corrupting heap management. It's the heap that gets confused and crashes the program.
positions[j+i*n][2]=i

in other words, 2 is not a valid index
Topic archived. No new replies allowed.