1

I have been running this random walk simulation for a while now and I keep getting an error EXC_BAD_ACCESS from Xcode. Its printing out a large part of the simulation though.

I think its running out of memory for some reason but I am not sure why.

If I go towards the end of the array I edited it so I don't get within 100 spaces of the edge (by editing the variable steps to steps -100). This works but I would like to know whats going on.

Any help would be appreciated.

double** places; places = (double**) malloc(steps*sizeof(double*)); for (int i = 0; i < steps; i++)places[i] = (double*) malloc(2*sizeof(double)); for (i = 0; i< steps/*, exit*/; i++) { // Find the angle of movement angle = getRand()*360; // Take a step xPos+= STEP*cos(angle); yPos+= STEP*sin(angle); //Write Step to array places[i][1] = xPos; places[i][2] = yPos; //Write Step to File fprintf(ff, "%d %lf %lf\n",i,xPos,yPos); } 

5 Answers 5

7

Array indexes start at zero.

Did you mean to write this?

 places[i][0] = xPos; //Zeroth element is considered the first element places[i][1] = yPos; //Second element 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh thank God! Now I feel like an idiot. I knew this but i totally mixed it up.
No problems. It happens to the best of us :)
0

You've allocated an array of the proper size (steps x 2), but you're writing to the wrong offsets on the sub-arrays. They should be [0] and [1], not [1] and [2].

[2] is actually the 3rd array element, so you're writing outside of the subarray's bounds.

Comments

0

The inner arrays (located at places[i]) have space for two elements - indexed by [0] and [1], since array indices generally start at zero in C. Here, you index them with [1] and [2]. You need to use [0] and [1] instead, or allocate enough space for three elements (and waste the space allocated for [0]).

Comments

0

Indexing starts from 0.

This should be:

places[i][0] = xPos; places[i][1] = yPos; 

Comments

0

You're off by one. Arrays in C are zero-based, so the first element is at position 0. You need to change your assignment to the places array as follows:

// Write Step to array places[i][0] = xPos; places[i][1] = yPos; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.