Crash sometimes occurs when retrieving a pointer from a TArray

for (int i = 0; i < GrabbedPrimitives.Num(); i++)
{
if (i >= GrabbedPrimitives.Num()) return;
if (!IsValid(GrabbedPrimitives[i])) continue;
UPrimitiveComponent* GrabbedPrimitive = GrabbedPrimitives[i];
}

Above is the bit of code causing the crash. It seems to break at ‘if (!IsValid(GrabbedPrimitives[i])) continue;’. I originally thought it was because of a null pointer issue so I added the IsValid check but that didn’t seem to fix things. I even added the check at the start of the loop to see if the array somehow changed size. Any ideas of what else could be causing the crash?

The array contains PrimitiveComponents for pawns, the pawns can be destroyed at any time before or after the loop, but not during it. The PrimitiveComponent is never destroyed by itself and the script calling this code is never destroyed. If it helps I’m using UE4 4.18.1.

You should consider installing the engine’s debugging symbols, which will present you with a specific exception/error message when crashes occur, as well as enabling you to run debugging sessions with your project using Visual Studio.

Without a specific error message, for now — I’m just guessing here — it might be that the IsValid(...) call is encountering something that it considers an assert condition, triggering an intentional crash. Hard to say without seeing the assert message (if there is one).

Nonetheless, try changing your IsValid(...) check to a simple comparison against nullptr, if you haven’t already tried that. More specifically, try changing line 4 in your pasted code to:

if (GrabbedPrimitives[i] == nullptr) continue;

That’s sufficient to determine whether the pointer can be de-referenced, though it won’t guarantee that the pointed-to object is valid in other ways (which is what IsValid() is good for).

If that quick change doesn’t solve your crashing problem, the next step would be to check your log files or install the editor’s debugging symbols — or both — because more information is needed.