erincatto / box2d

Box2D is a 2D physics engine for games
https://box2d.org
MIT License
7.44k stars 1.47k forks source link

Unitialized data is referenced in 'b2PolygonShape::Set'. #743

Open charlie5 opened 1 year ago

charlie5 commented 1 year ago

The 'ps' array of 'b2Vec2' is not initialized and has no default constructor. This will lead to random data being fed to 'b2DistanceSquared'.

void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
    {
      b2Assert(3 <= count && count <= b2_maxPolygonVertices);
      if (count < 3)
      {
        SetAsBox(1.0f, 1.0f);
         return;
      }

      int32 n = b2Min(count, b2_maxPolygonVertices);

       // Perform welding and copy vertices into local buffer.
      b2Vec2 ps[b2_maxPolygonVertices];     // *** ps array declared here ***
      int32 tempCount = 0;
      for (int32 i = 0; i < n; ++i)
      {
         b2Vec2 v = vertices[i];

         bool unique = true;
         for (int32 j = 0; j < tempCount; ++j)
         {
            if (b2DistanceSquared(v, ps[j]) < ((0.5f * b2_linearSlop) * (0.5f * b2_linearSlop)))     // *** ps has not been initialized yet ***
            {
               unique = false;
               break;
            }
         }

         if (unique)
         {
            ps[tempCount++] = v;
         }
      }
kritma commented 1 year ago

int32 tempCount = 0 so "for (int32 j = 0; j < tempCount; ++j)" is skipped and ps initialized later if (unique) { ps[tempCount++] = v; }