Access violation with "null pointer check"

I am getting random crashes in my project, all related to this line of code, that closes all doors:
The error is a "Access violation - code c0000005 … "

for (ATrainDoor* TrainDoor : TrainDoors)
if(TrainDoor) TrainDoor->CloseTrainDoor(bLock); ← this line

I allready added the check, to make sure it is not a null pointer, why am I still getting the error?
I feels like I am missing something very obvious…

Thru it not very healthy thing to do try calling TrainDoor->IsValidLowLevel() insted of null checking, if it fix the problem that means you have invalid pointer in array for some reason, Invlid pointers are made when object is deleted but pointer is still pointing to it and pointer is nor formally null at this state, usually UPROPERTY() prevents that from happening, so check if you have it.

I guess the UPROPERTY will gix it, of course its hard to test, because the error occurs radonly and quite rarely, thanks for the tipp! Will help me very much in the future!

Hi there,

From your question and comments it appears your problem is that the pointer itself is being invalidated between calls.

That is to say, a pointer is an address in memory, quite literally just a number that leads to a location.
If you store an address it doesn’t provide any assurance the object pointed-to is valid, nor does it ensure you have not stored an invalid value in a pointer.

Just like having an address to your school-friends house doesn’t ensure that your friend hasn’t moved out, or the house been demolished.

In short, do not store a pointer to an object in the world if it is remotely possible to find that object via any other mechanism. If you absolutely must store a pointer to an actor that may be destroyed, removed or changed, please use a UProperty or smart pointer to prevent the pointer not being updated on the objects destruction.