Access violation on a TArray of FVectors when using Add()

I sometimes get the following error whenever I try to generate my chunks.

Exception thrown at 0x00007FF80028DDE4 (UnrealEditor-Bountiful.dll) in UnrealEditor.exe: 0xC0000005: Access violation writing location 0xFFFFFFFFFFFFFFE8.

I used the built in visual studio debugger and it brought me here


ting location 0xFFFFFFFFFFFFFFE8.

I don’t know what to do with this, I tried to use breakpoints but the error still shows. The error is attributed to RegenerateRenderDistanceChunks() at the line PendingChunkCoordinates.Add(Chunk);

No matter how many scopelocks I use I still get the exact same error

.CPP file the error is coming from

#include "Planet.h"
#include "FastNoiseWrapper.h"
#include "Chunk.h"
#include "RealtimeMeshComponent.h"
#include "RealtimeMeshSimple.h"
#include "UObject/ConstructorHelpers.h"
#include "Misc/ScopeLock.h"
#include "HAL/PlatformTime.h"

// Sets default values
APlanet::APlanet()
{
    RenderDistance = 12;

    // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    NoiseWrapper = CreateDefaultSubobject<UFastNoiseWrapper>(TEXT("NoiseWrapper"));
    fastNoiseWrapper = CreateDefaultSubobject<UFastNoiseWrapper>(TEXT("FastNoiseWrapper"));

    ConstructorHelpers::FObjectFinder<UMaterial> MaterialAsset(TEXT("Material'/Script/Engine.Material'/Game/Materials/Grass.Grass''"));
    if (MaterialAsset.Succeeded())
    {
        ChunkMaterial = MaterialAsset.Object;
    }

    RealtimeMeshComponent = CreateDefaultSubobject<URealtimeMeshComponent>(TEXT("RealtimeMeshComponent"));
    RealtimeMeshComponent->SetMobility(EComponentMobility::Movable);
    RealtimeMeshComponent->SetGenerateOverlapEvents(false);
    RealtimeMeshComponent->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);
    SetRootComponent(RealtimeMeshComponent);
    RealtimeMeshComponent->SetMaterial(0, ChunkMaterial);
}

// Called when the game starts or when spawned
void APlanet::BeginPlay()
{
    Super::BeginPlay();

    SetPlayerSpawnPosition();

    RealtimeMesh = RealtimeMeshComponent->InitializeRealtimeMesh<URealtimeMeshSimple>();

    CharacterPosition = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();
    LastCharacterPosition = CharacterPosition;
    PlayerChunkCoord = GetChunkFromVector3(CharacterPosition);
    LastPlayerChunkCoord = PlayerChunkCoord;

    if (fastNoiseWrapper)
    {
        fastNoiseWrapper->SetupFastNoise(EFastNoise_NoiseType::Perlin, 13317);
    }
    else
    {
        GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("fastNoiseWrapper is null"));
    }

    GenerateWorld();
}

void APlanet::SetPlayerSpawnPosition() {
    int32 xPos = FMath::RandRange(-1000, 1000);
    int32 yPos = FMath::RandRange(-1000, 1000);

    FVector ScaledPosition = FVector(xPos, yPos, 0) * 0.1;

    GetWorld()->GetFirstPlayerController()->GetPawn()->SetActorLocation(FVector(
        xPos * VOXEL_SIZE_IN_UNITS,
        yPos * VOXEL_SIZE_IN_UNITS,
        (((fastNoiseWrapper->GetNoise2D(ScaledPosition.X, ScaledPosition.Y) + 1) / 2) * CHUNK_SIZE_IN_VOXELS * VOXEL_SIZE_IN_UNITS * 10) + 350
    ));
}

void APlanet::CreateChunk(FVector ChunkCoord) {
    if (ActiveChunks.Contains(ChunkCoord)) {
        return;
    }

    FVector WorldPosition = ChunkCoord * CHUNK_SIZE_IN_VOXELS * VOXEL_SIZE_IN_UNITS;

    ActiveChunks.Add(ChunkCoord);
    int index = ActiveChunkReferences.Add(new FChunk(ChunkCoord, this, WorldPosition));
    ActiveChunkReferences[index]->InitializeChunk();
}

void APlanet::GenerateWorld()
{
    for (int x = PlayerChunkCoord.X - RenderDistance; x <= PlayerChunkCoord.X + RenderDistance; x++)
    {
        for (int y = PlayerChunkCoord.Y - RenderDistance; y <= PlayerChunkCoord.Y + RenderDistance; y++)
        {
            for (int z = PlayerChunkCoord.Z - RenderDistance; z <= PlayerChunkCoord.Z + RenderDistance; z++)
            {
                FVector ChunkPosition = FVector(x, y, z);
                CreateChunk(ChunkPosition);
            }
        }
    }
}

void APlanet::RegenerateRenderDistanceChunks()
{
    FScopeLock Lock(&RegenerateRenderDistance);
    if (CurrentlyCheckingViewDistance) {
        return;
    }
    CurrentlyCheckingViewDistance = true;

    double StartTime = FPlatformTime::Seconds(); // Start timing

    int32 NumChunks = (RenderDistance * 2 + 1) * (RenderDistance * 2 + 1) * (RenderDistance * 2 + 1);
    TSet<FVector> NewChunks;
    NewChunks.Reserve(NumChunks);
    PendingChunkCoordinates.Empty();

    for (int x = PlayerChunkCoord.X - RenderDistance; x <= PlayerChunkCoord.X + RenderDistance; x++)
    {
        for (int y = PlayerChunkCoord.Y - RenderDistance; y <= PlayerChunkCoord.Y + RenderDistance; y++)
        {
            for (int z = PlayerChunkCoord.Z - RenderDistance; z <= PlayerChunkCoord.Z + RenderDistance; z++)
            {
                if (IsChunkInWorld(FVector(x, y, z))) {
                    NewChunks.Add(FVector(x, y, z));
                }
            }
        }
    }

    if (!NewChunks.IsEmpty()) {
        FScopeLock Lock2(&MyCriticalSection);
        for (const FVector& Chunk : ActiveChunks)
        {
            if (!NewChunks.Contains(Chunk)) {

                PendingChunkDeletions.Add(Chunk);
            }
        }
    }
    
    if (!NewChunks.IsEmpty()) {
        FScopeLock Lock2(&MyCriticalSection);
        for (const FVector& Chunk : NewChunks)
        {
            if (!ActiveChunks.Contains(Chunk)) {
                PendingChunkCoordinates.Add(Chunk);
            }
        }
    }

    CurrentlyCheckingViewDistance = false;

    double EndTime = FPlatformTime::Seconds(); // End timing
    UE_LOG(LogTemp, Warning, TEXT("RegenerateRenderDistanceChunks took %f seconds"), EndTime - StartTime);
}

void APlanet::RemoveChunk(FVector ChunkCoord)
{

    int32 Index = ActiveChunks.IndexOfByKey(ChunkCoord);
    if (Index != INDEX_NONE)
    {
        const FRealtimeMeshSectionGroupKey GroupKey = FRealtimeMeshSectionGroupKey::Create(0, FName(ChunkCoord.ToCompactString()));
        const FRealtimeMeshSectionKey PolyGroup0SectionKey = FRealtimeMeshSectionKey::CreateForPolyGroup(GroupKey, 0);

        // Now we create the section group, since the stream set has polygroups, this will create the sections as well
        RealtimeMesh->RemoveSectionGroup(GroupKey);

        ActiveChunkReferences[Index]->DestroySelf();
        ActiveChunkReferences.RemoveAt(Index);
        ActiveChunks.RemoveAt(Index);
    }
}

int APlanet::GetVoxel(FVector Position)
{

    FVector ScaledPosition = Position * 0.1;
    float NoiseValue = ((fastNoiseWrapper->GetNoise2D(ScaledPosition.X, ScaledPosition.Y) + 1) / 2) * CHUNK_SIZE_IN_VOXELS;

    // Return voxel type based on noise value, for now returning a placeholder value
    if (Position.Z <= NoiseValue * 10) {
        return 1;
    }
    else
    {
        return 0;
    }
}

bool APlanet::IsChunkInWorld(FVector ChunkCoord) const
{
    return true; // You should implement your own logic here
}

// Called every frame
void APlanet::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    CharacterPosition = GetWorld()->GetFirstPlayerController()->GetPawn()->GetActorLocation();
    PlayerChunkCoord = GetChunkFromVector3(CharacterPosition);

    if (PlayerChunkCoord != LastPlayerChunkCoord) {
        NeedsToRegenerateRenderDistance = true;
    }

    if (NeedsToRegenerateRenderDistance && !CurrentlyCheckingViewDistance) {
        NeedsToRegenerateRenderDistance = false;
        AsyncTask(ENamedThreads::AnyHiPriThreadNormalTask, [this]() {
            /* Work on the TaskGraph */
            this->RegenerateRenderDistanceChunks();
            });
    }


    int ChunksCreatedThisFrame = 0;
    if (!PendingChunkCoordinates.IsEmpty()) {

        FScopeLock Lock(&MyCriticalSection);

        while (PendingChunkCoordinates.Num() > 0 && ChunksCreatedThisFrame < MaxChunkCreationsPerFrame)
        {
            FVector ChunkPosition = PendingChunkCoordinates[0];
            {
                PendingChunkCoordinates.RemoveAt(0);
            }
            CreateChunk(ChunkPosition);
            ChunksCreatedThisFrame++;
        }
    }

    int ChunksDeletedThisFrame = 0;
    if (!PendingChunkDeletions.IsEmpty()) {
        FScopeLock Lock(&MyCriticalSection);
        while (PendingChunkDeletions.Num() > 0 && ChunksDeletedThisFrame < MaxChunkDeletionsPerFrame)
        {
            FVector ChunkPosition = PendingChunkDeletions[0];
            {
                PendingChunkDeletions.RemoveAt(0);
            }
            RemoveChunk(ChunkPosition);
            ChunksDeletedThisFrame++;
        }
    }
    LastCharacterPosition = CharacterPosition;
    LastPlayerChunkCoord = PlayerChunkCoord;
}

FVector APlanet::GetChunkFromVector3(FVector WorldPosition)
{
    FVector ChunkCoord = WorldPosition / (CHUNK_SIZE_IN_VOXELS * VOXEL_SIZE_IN_UNITS);
    ChunkCoord.X = FMath::FloorToInt(ChunkCoord.X);
    ChunkCoord.Y = FMath::FloorToInt(ChunkCoord.Y);
    ChunkCoord.Z = FMath::FloorToInt(ChunkCoord.Z);

    if (IsChunkInWorld(ChunkCoord))
    {
        return ChunkCoord;
    }

    return FVector(-1, -1, -1); // Return an invalid coordinate if the chunk is not in the world
}

FVector APlanet::GetChunkFromVoxel(FVector VoxelPosition)
{
    FVector ChunkCoord = VoxelPosition / CHUNK_SIZE_IN_VOXELS;
    ChunkCoord.X = FMath::FloorToInt(ChunkCoord.X);
    ChunkCoord.Y = FMath::FloorToInt(ChunkCoord.Y);
    ChunkCoord.Z = FMath::FloorToInt(ChunkCoord.Z);

    if (IsChunkInWorld(ChunkCoord))
    {
        return ChunkCoord;
    }

    return FVector(-1, -1, -1); // Return an invalid coordinate if the chunk is not in the world
}
````Preformatted text`

Error in logs:

[2024.07.06-15.25.26:797][708]LogThreadingWindows: Error: Runnable thread Foreground Worker #0 crashed.
[2024.07.06-15.25.26:798][708]LogWindows: Error: === Critical error: ===
[2024.07.06-15.25.26:798][708]LogWindows: Error:
[2024.07.06-15.25.26:798][708]LogWindows: Error: Fatal error!
[2024.07.06-15.25.26:798][708]LogWindows: Error:
[2024.07.06-15.25.26:798][708]LogWindows: Error: Unhandled Exception: EXCEPTION_ACCESS_VIOLATION writing address 0xffffffffffffffe8
[2024.07.06-15.25.26:798][708]LogWindows: Error:
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff800e6dde4 UnrealEditor-Bountiful.dll!APlanet::RegenerateRenderDistanceChunks() [C:\Users\zubid\Documents\Unreal Projects\Bountiful\Source\Bountiful\Planet.cpp:145]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928c0c26 UnrealEditor-Core.dll!TGraphTask::ExecuteTask() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Public\Async\TaskGraphInterfaces.h:1235]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928ab7bd UnrealEditor-Core.dll!LowLevelTasks::FTask::Init<FTaskGraphCompatibilityImplementation::QueueTask’::5'::<lambda_1> >'::13’::<lambda_1>::operator()() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Public\Async\Fundamental\Task.h:499]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928b4c83 UnrealEditor-Core.dll!LowLevelTasks::TTaskDelegate<LowLevelTasks::FTask * __cdecl(bool),48>::TTaskDelegateImpl<LowLevelTasks::FTask::Init<FTaskGraphCompatibilityImplementation::QueueTask’::5'::<lambda_1> >'::13’::<lambda_1>,0>::CallAndMove() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Public\Async\Fundamental\TaskDelegate.h:171]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928c24c5 UnrealEditor-Core.dll!LowLevelTasks::FTask::ExecuteTask() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Public\Async\Fundamental\Task.h:627]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928c21ff UnrealEditor-Core.dll!LowLevelTasks::FScheduler::ExecuteTask() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Private\Async\Fundamental\Scheduler.cpp:155]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928ea155 UnrealEditor-Core.dll!LowLevelTasks::FScheduler::WorkerMain() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Private\Async\Fundamental\Scheduler.cpp:397]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff8928b23d0 UnrealEditor-Core.dll!UE::Core::Private::Function::TFunctionRefCaller<LowLevelTasks::FScheduler::CreateWorker'::2’::<lambda_1>,void __cdecl(void)>::Call() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Public\Templates\Function.h:406]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff892ab7c93 UnrealEditor-Core.dll!FThreadImpl::Run() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Private\HAL\Thread.cpp:69]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff892f1c93d UnrealEditor-Core.dll!FRunnableThreadWin::Run() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Private\Windows\WindowsRunnableThread.cpp:149]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff892f102b7 UnrealEditor-Core.dll!FRunnableThreadWin::GuardedRun() [D:\build++UE5\Sync\Engine\Source\Runtime\Core\Private\Windows\WindowsRunnableThread.cpp:79]
[2024.07.06-15.25.26:798][708]LogWindows: Error: [Callstack] 0x00007ff981e3257d KERNEL32.DLL!UnknownFunction
[2024.07.06-15.25.26:798][708]LogWindows: Error:
[2024.07.06-15.25.26:798][708]LogWindows: Error: Crash in runnable thread Foreground Worker #0
[2024.07.06-15.25.26:803][708]LogExit: Executing StaticShutdownAfterError
[2024.07.06-15.25.26:809][708]LogWindows: FPlatformMisc::RequestExit(1, FRunnableThreadWin::GuardedRun.ExceptionHandler)
[2024.07.06-15.25.26:809][708]LogWindows: FPlatformMisc::RequestExitWithStatus(1, 3, FRunnableThreadWin::GuardedRun.ExceptionHandler)
[2024.07.06-15.25.26:809][708]LogCore: Engine exit requested (reason: Win RequestExit)

Heres a video of what it looks like