[C++] How to prevent crashes when programming in UE4?

Hi, I need to know if there is some sort of cheatsheet about prevent variables crashing the engine, this because some things are perfectly fine when compiling, but on press play they silently will crash the engine.
I wish to know if for example variables have a check like:

TArray.isValid
or
isValid(pointer)

or something else.

I want to avoid the hassle to check on crashes everytime view symbols or write code that compile fine but fail everytime.

Thanks for helping me!

The most common crash reason is nullptr instead of an actual object.

There are 2 main approaches I know:

  1. to build such an architecture which will make things sure to be available. It’s a complex way and requires a senior-level experience to implement properly.
  2. Just check your pointers with IsValid(pointer) right after getting it and prepare something in case if pointer is not valid.

For instance, if you’re in AController-derived class and going to use GetPawn() method:

AActor* MyPawn = GetPawn();
if (!IsValid(MyPawn)) {
    // just return if possible or maybe do some fallback here
    return;
}

// Do something with MyPawn here

Though there are no such checks for structures, since they are always exist, just can be with default values – so you need to make some manual checks for structures, if it’s needed.

Also you should add the UPROPERTY() macro for any member derived from UObject (including AActor and so on) – it will make them work properly with garbage collection, otherwise you can face nullptr even when the object should exist.

Another common crash reason is accessing a TArray or TMap with an index which does not exist. For TArray there is the method for it: MyArray.IsValidIndex(Index). For TMap it’s MyMap.Contains(Key).

Thank you very much :slight_smile: !