title: C memory management with 2D arrays
body: <p>I'm starting to play around with some C code within Objective-C programs. The function I'm trying to write sorts all of the lat/long coordinates from a KML file into clusters based on 2D arrays.</p>
  
  <p>I'm using three 2D arrays to accomplish this:</p>
  
  <p><code>NSUInteger **bucketCounts</code> refers to the number of <code>CLLocationCoordinate2D</code>s in a cluster.</p>
  
  <p><code>CLLocationCoorindate2D **coordBuckets</code> is an array of arrays of coordinates</p>
  
  <p><code>NSUInteger **bucketPointers</code> refers to an index in the array of coordinates from <code>coordBuckets</code></p>
  
  <p>Here's the code that is messing me up:</p>
  
  <pre><code>//Initialize C arrays and indexes
  int n = 10;
  bucketCounts = (NSUInteger**)malloc(sizeof(NSUInteger*)*n);
  bucketPointers = (NSUInteger**)malloc(sizeof(NSUInteger*)*n);
  coordBuckets = (CLLocationCoordinate2D **)malloc(sizeof(CLLocationCoordinate2D*)*n);
  
  for (int i = 0; i &lt; n; i++) {
      bucketPointers[i] = malloc(sizeof(NSUInteger)*n);
      bucketCounts[i] = malloc(sizeof(NSUInteger)*n);
  }
  NSUInteger nextEmptyBucketIndex = 0;
  int bucketMax = 500;
  </code></pre>
  
  <p>Then for each <code>CLLocationCoordinate2D</code> that needs to be added:</p>
  
  <pre><code>//find location to enter point in matrix
  int latIndex = (int)(n * (oneCoord.latitude - minLat)/(maxLat-minLat));
  int lonIndex = (int)(n * (oneCoord.longitude - minLon)/(maxLon-minLon));
  
  //see if necessary bucket exists yet. If not, create it.
  NSUInteger positionInBucket = bucketCounts[latIndex][lonIndex];
  if (positionInBucket == 0) {
      coordBuckets[nextEmptyBucketIndex] = malloc(sizeof(CLLocationCoordinate2D) * bucketMax);
      bucketPointers[latIndex][lonIndex] = nextEmptyBucketIndex;
      nextEmptyBucketIndex++;
  }
  
  //Insert point in bucket.
  NSUInteger bucketIndex = bucketPointers[latIndex][lonIndex];
  CLLocationCoordinate2D *bucketForInsert = coordBuckets[bucketIndex];
  bucketForInsert[positionInBucket] = oneCoord;
  bucketCounts[latIndex][lonIndex]++;
  positionInBucket++;
  
  //If bucket is full, expand it.
  if (positionInBucket % bucketMax == 0) {
      coordBuckets[bucketIndex] = realloc(coordBuckets[bucketIndex], (sizeof(CLLocationCoordinate2D) * (positionInBucket + bucketMax)));
  }
  </code></pre>
  
  <p>Things seem to be going well for about 800 coordinates, but at the same point a value in either <code>bucketCounts</code> or <code>bucketPointers</code> gets set to an impossibly high number, which causes a reference to a bad value and crashes the program. I'm sure this is a memory management issue, but I don't know C well enough to troubleshoot it myself. Any helpful pointers for where I'm going wrong? Thanks!</p>