Access Violation on TArray::Add in actor component

I get this error when I start the game in the editor

Access violation - code c0000005 (first/second chance not available)
UE4Editor_SwordTest_5676!UPlayerActionComponent::AddAction() [e:_unreal_projects\swordtest\source\swordtest\playeractioncomponent.cpp:22]
UE4Editor_SwordTest_5676!APlayerCharacter::BeginPlay() [e:_unreal_projects\swordtest\source\swordtest\characters\playercharacter.cpp:86]
UE4Editor_Engine!AActor::DispatchBeginPlay() [d:\build++ue4+release-4.18+compile\sync\engine\source\runtime\engine\private\actor.cpp:3160]

Here’s the relevant code

// PlayerCharacter.h
UPlayerActionComponent* ActionComponent;

// PlayerCharacter.cpp 
// APlayerCharacter::APlayerCharacter()
ActionComponent = CreateDefaultSubobject<UPlayerActionComponent>(
// APlayerCharacter::BeginPlay()

// PlayerActionComponent.h
TArray<int> MyArray;

// PlayerActionComponent.cpp UPlayerActionComponent::AddAction

It doesn’t only crash on Add, but also Empty, Num, even assigning a new array MyArray = TArray<int>(). I’ve gotten this error many times now, on different classes using TArray or TMap, so I must be doing something consistently wrong but I can’t figure out what.
I feel like it just comes and goes. For example it was working fine, then I restarted the editor, got this message


and now it crashes again after recompiling even though I didn’t change the code.

Hey there if you do it as a local variable in the playercharacter constructor, does it still happen?

I just noticed that IsValid(ActionComponent) returns false soon after creation, I am guessing it is being garbage collected? But I don’t know why.

The UPROPERTY on the component should prevent it from being GC’d, try adding something more like BlueprintReadOnly, Category = “Test”.

I’ve tried many combinations now and I don’t see the error anymore, however I can’t be quite sure what caused it in the first place.