Strange array overflow (aka WTF I missing here?)

Started by
2 comments, last by Ectara 10 years ago
So I have this fun little function, which reliably crashes at line D (commented below), only if TILE_SIZE is set to an odd number:
const int TILE_SIZE = 7;

Tile *create(const std::array<vector3, 4> &corners) {
   std::vector<vector3> verts; // line A
   std::array<vector3, TILE_SIZE/2> past; // line B

   for (int i = 0; i < TILE_SIZE; ++i) {
      vector3 hi = cml::lerp(corners[0], corners[1], i / float(TILE_SIZE-1));
      vector3 lo = cml::lerp(corners[3], corners[2], i / float(TILE_SIZE-1));

      for (int j = 0; j < TILE_SIZE; ++j) {
         vector3 v = cml::lerp(lo, hi, j / float(TILE_SIZE-1)) );

         if (((i & 1) == 0 || i == TILE_SIZE-1) && ((j & 1) == 0 || j == TILE_SIZE-1)) {
            past[j/2] = v; // line C
         }

         verts.push_back(v); // line D
         verts.push_back(past[j/2]);
      }
   }

// ...
}
The debugger tells me that this is because the verts array has an impossibly large size, which can be fixed by increasing the size of the past array by 1, commenting line C, or swapping lines A and B.

"Array overflow", you say, "silly dev has an off-by-one error in line C", you say. And I'd agree with you, except I can't see it for the life of me. With TILE_SIZE=7, the past array should have a length of 7/2=3, and the inner for loop counts up to (7-1)/2=3, which seems fine, and has been validated with much printf-debugging...

Any ideas to relieve my current anxiety?

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Advertisement

If TILE_SIZE is 7, then the loop goes from j=0 to j=6. When j is equal to 6, it tries to push past[j/2] onto verts. Since past has a length of TILE_SIZE/2 or 3, its valid indices go from 0 to 2. I am not sure at the moment how to fix this though.

its valid indices go from 0 to 2.

Crap. After all these years, zero-based indexing still occasionally trips me up. And another pair of eyes always helps smile.png

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

Try setting the past array size to ((TILE_SIZE + 1) / 2)? Though, I'm sure solutions are forthcoming now that the problem is pointed out.

This topic is closed to new replies.

Advertisement