box2d icon indicating copy to clipboard operation
box2d copied to clipboard

Possible memory access issue in ShapeDistance sample (invalid m_simplexIndex initialization)

Open ikpil opened this issue 2 months ago • 2 comments

In the ShapeDistance sample, the following code exists:

if (m_drawSimplex)
{
    b2Simplex* simplex = m_simplexes + m_simplexIndex;
    b2SimplexVertex* vertices[3] = { &simplex->v1, &simplex->v2, &simplex->v3 };
}

When porting this code to C#, I encountered an array reference exception. Upon checking the original C++ code, I found that m_simplexIndex is initialized to -1, which can cause memory access violations when used in the above statement.

Please review this behavior — it seems that accessing m_simplexes + m_simplexIndex before proper initialization may lead to undefined behavior.

ikpil avatar Nov 02 '25 05:11 ikpil

I don't see it being initialized to -1. What line number?

erincatto avatar Nov 02 '25 17:11 erincatto

https://github.com/erincatto/box2d/blob/3a4f0da8374af61293a03021c9a0b3ebcfe67948/samples/sample_collision.cpp#L222

		if ( ImGui::Checkbox( "draw simplex", &m_drawSimplex ) )
		{
			m_simplexIndex = 0;
		}

		if ( m_drawSimplex )
		{
			ImGui::SliderInt( "index", &m_simplexIndex, 0, m_simplexCount - 1 );
			m_simplexIndex = b2ClampInt( m_simplexIndex, 0, m_simplexCount - 1 ); // <-------------- this!
		}

ikpil avatar Nov 03 '25 11:11 ikpil

Thanks for the report. Fixed in #1022

erincatto avatar Dec 15 '25 00:12 erincatto