Download

Editor crash when using certain function

Hello everyone,

I’m currently facing a problem and don’t know how to resolve it…There is one function in my code that makes the game crash after a few seconds if it’s called every tick. I’m assuming it has something to do with improper memory management from my side since everything works perfectly fine if I don’t call this function anymore. Here’s what the function looks like:



/**
 * returns all tiles which are no further than the specified distance (in grid coordinates, not reachability)
 */
TArray<ATile*> ULevelManager::GetTilesWithMaxDistance(ATile* StartTile, uint8 MaxDistance)
{
    TArray<ATile*> CloseTiles;

    for (ATile* Tile : this->Tiles)
    {
        int distance = UKismetMathLibrary::Abs(Tile->GridPosition.X - StartTile->GridPosition.X) + UKismetMathLibrary::Abs(Tile->GridPosition.Y - StartTile->GridPosition.Y);

        if (distance <= MaxDistance)
        {
            CloseTiles.Add(Tile);
        }
    }

    return CloseTiles;
}


Does anybode see why this function could cause a crash if it is called every tick?

Thank you for your help :smiley:
Bugmee

Always check if an object pointer is a valid object.

C++ doesn’t do that for you, if the object is nullptr or invalid memory and you try to access that object everything will explode in front of you.

Use the ‘Assert’ library to debug your code:

I indeed got a nullptr. Thank you!

That does raise some other questions though :smiley: Why do I get a nullptr to a tile reference when it is an actor in the scene and I didn’t destroy it anywhere? I thought actors are not garbage collected until you destroy them.

You have an array of pointers, not an array of AActors;

“Tiles” should be a UProperty() and everytime you make changes to it you should call TArray::Shrink() on it to make sure your pointers are fresh and clean.

Okay, I see. Assuming I want to keep a reference to all my tiles during the whole game, how should I proceed then? Because I assume TArray::Shrink() only gets rid of the invalid pointers