title: CUDA (JCUDA) shared memory (?) problems / undefined behaviour
body: <p>Im working on my game project (tower defence) and Im trying to compute the distance between all criters and a tower with JCuda using the shared memory. For each tower I run 1 block with N threds, where N equals the number of critters on the map. Im computing distance between all criters and that tower for given block, and I store the smallest found distance so far in the block's shared memory. My current code looks like that:</p>
  
  <pre><code>extern "C"
  
  __global__ void calcDistance(int** globalInputData, int size, int
  critters, int** globalQueryData, int* globalOutputData) {
  
   //shared memory
   __shared__ float minimum[2];
  
   int x = threadIdx.x  + blockIdx.x * blockDim.x;
   int y = blockIdx.y;
  
   if (x &lt; critters) {
  
     int distance = 0;
     //Calculate the distance between tower and criter
     for (int i = 0; i &lt; size; i++) {
       int d = globalInputData[x][i] - globalQueryData[y][i];
       distance += d * d;
     }
  
     if (x == 0) {        
       minimum[0] = distance;
       minimum[1] = x;
     }
  
     __syncthreads();
  
  
  
     if (distance &lt; minimum[0]) {
       minimum[0] = distance;
       minimum[1] = x;
     }
  
     __syncthreads();
     globalOutputData[y * 2]     = minimum[0];
     globalOutputData[y] = minimum[1];
  
   }
  
  
  }
  </code></pre>
  
  <p>The <strong>problem</strong> is if I rerun the code using the same input multiple times (I free all the memory on both host and device after each run) I get different output each time I the code gets executed for blocks (tower) number > 27... Im fairly sure it has something to do with the shared memory and the way im dealing with it, as rewriting the code to use global memory gives the same result whenever the code gets executed. Any ideas?</p>