Search code examples
pointersshared-ptr

Segfault in factory constructed class


I have an issue where a Segfault occurs in random locations but those locations seem to always be the same. The issue also is made more confusing by the fact that the location of the Segfault can change depending on whether I'm using gdb or valgrind to try and solve the issue. This would seem to be a race condition problem but I don't always see any of my destructors being called so I'm not sure why that would be happening. I have not defined my copy constructors which I suppose could be the problem but I would like to understand why that may be.

The tests that I have on the midLevel class to exercise its functionality don't have this problem. Is there something flawed with my basic construction?

My use case is:

In highest level class:

returnObject highLevelClass::performTask( ){

    std::shared_ptr< midLevelClass > midClass;
    std::vector< someType > dataForClass;

    for ( auto it = _someIterate.begin( ); it != _someIterate.end( ); it++ ){

        ...
        buildMidClass( midClass, &dataForClass );

    }

    ...

    return returnObject;

}

returnObject highLevelClass::buildMidClass( std::shared_ptr< midLevelClass > &midClass,
                                            std::vector< someType > *dataForClass ){

    ...
    midClass = midLevelClass( _configurationInfo ).create( )
    midClass.loadData( dataForClass );

    midClass->processData( ); //SOMETIMES IT SEGFAULTS HERE DURING std::vector ALLOCATIONS

    ...

    return returnObject;
}

highLevelClass::~highLevelClass( ){

    //SOMETIMES IT SEGFAULTS HERE

    return;

}

In the mid-level class:

midLevelClass::loadData( std::vector< someType > *data ){

    _data = data; //_data is a std::vector< someType >*

}

std::shared_ptr< midLevelClass > midLevelClass::create( configurationType &_configInfo ){

    if ( _configInfo[ "type" ] == childMidLevelClass ){
        return std::make_shared< childMidLevelClass >( _configInfo );
    }

    _error = new errorNode( "create", "The type is not defined" );
    return std::make_shared< volumeReconstructionBase >( _config, _error );
}

Solution

  • The answer turned out to be that another std::vector ( that wasn't being accessed by any other part of the code ) was overflowing through a bad access using []. Nothing in gdb or valgrind showed that this was the problem. The answer is probably be careful about using [] to access a std::vector and consider using std::vector::at( ).