• Advertisement
Sign in to follow this  

Strange array overflow (aka WTF I missing here?)

This topic is 1383 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement