Search code examples
c++bulletphysics

Bullet Physics First Chance Exception When Creating New btConvexHullShape


When I create a new btConvexHullShape I get a first chance exception. Code is:

btConvexHullShape* m_collisionShapes;
m_collisionShapes = static_cast<btConvexHullShape*>(malloc(sizeof(btConvexHullShape)* MAX_BODY_COUNT));
new (&m_collisionShapes[m_activeBodyCount]) btConvexHullShape();

I also tried:

std::vector<btConvexHullShape> m_hulls;
m_hulls.resize(MAX_BODY_COUNT);

The exception occurs at the new call and the resize call. The exception is:

  Unhandled exception at 0x0102C983 in Useful_Engine.exe: 
0xC0000005: Access violation reading location 0xFFFFFFFF.

And it occurs inside of the bullet source code at:

/**@brief Return the elementwise product of two vectors */
SIMD_FORCE_INLINE btVector3 
operator*(const btVector3& v1, const btVector3& v2) 
{
#if defined(BT_USE_SSE_IN_API) && defined (BT_USE_SSE)
    return btVector3(_mm_mul_ps(v1.mVec128, v2.mVec128));
#elif defined(BT_USE_NEON)
    return btVector3(vmulq_f32(v1.mVec128, v2.mVec128));
#else
    return btVector3(
            v1.m_floats[0] * v2.m_floats[0], 
            v1.m_floats[1] * v2.m_floats[1], 
            v1.m_floats[2] * v2.m_floats[2]);
#endif
}

Is this a known problem ?


Solution

  • It looks like a memory alignment problem. Keep in mind that almost all Bullet data types are aligned. Bullet overrides "new" operators for them. Using malloc and vectors is dangerous with bullet types. Instead of using vectors, you should use btAlignedObjectArray. If you REALLY need to allocate memory manually, you can try to use aligned allocation. For memory allocation bullet uses btAlignedAlloc. Or you can just create your array in the following way:

    btAlignedObjectArray<btConvexHullShape> m_hulls;
    m_hulls.resize(MAX_BODY_COUNT);