Empty check on TArray<AActor*> throws an exception

When checking .IsEmpty() or .Num() == 0 or .IsValidIndex(0) on TArray<AActor*> , it crashes Unreal!!! (EXCEPTION_ACCESS_VIOLATION reading address)

Can someone help with this? it’s so annoying…

I added UPROPERTY() to the header file but still not change…

what about just validate the array?

TArray<AActor*> MyArray;
.
.
if (MyArray)
{
.
.
.
}

I think when you use IsEmpty() or .Num() the system asumes MyArray is valid.
the pointer of an array is = the pointer of the first item.
if there is not array AT ALL then you cant tell how many elements it holds (.Num())

I tried that too but it says: expression must have bool type (or be convertible to bool)

Arrays are not pointers as in an Array can’t be invalid. I think the debugger is misleading you.

Show your code.

header:

UPROPERTY()
	TArray<AActor*> ItemsCarried;

CPP:

bool UInventory::IsItemInInventory(FName ItemName) const
{
	if (!ItemsCarried.IsEmpty()) {
		for (int i = 0; i < ItemsCarried.Num(); i++)
		{
			AActor* Item = ItemsCarried[i];
			if (Item->ActorHasTag(ItemName)) return true;
		}
	}
	return false;
}

It crashes exactly on the if (!ItemsCarried.IsEmpty()) EXCEPTION_ACCESS_VIOLATION reading address.

Best guess is that UInventory is being garbage collected but still alive somehow.
Try this before accessing the member Array.

IsPendingKill()

Where are you calling this?

Inside of my gameplay? whenever my player presses a button it should do that.

TArray<AActor*> Items;
AActor* ItemActor = Spawn bla bla bla;
Items.Add(ItemActor);
ItemActor->Destroy();

if(Items[0] != nullptr)
{
// ItemActor already destroyed completely, but still it is valid pointer in Array Reference

Items[0]->DoSomething(); // Crash, because ItemActor is actually not valid
}
  • Similarly, if we do something with Array when it’s values are not valid like this, it may crash.
  • So make sure to manually remove from array if actor is destroyed or pending destroy.

I can’t even check the array man. The engine thinks the array itself is a problem not it’s content. I can’t even do Items[0] or .IsEmpty() or .Num() == 0 or .IsValidIndex(0) on it.

Even when I get an accessor function to access the array and return it:

TArray<AActor*> UInventory::GetItemsCarried() const
{
	return ItemsCarried;
}

It still crashes on the line that says ItemsCarried.

The problem was I forgot to add the component to my character LMAO.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.