Setting Timers - nullptr Question?

Hi All,

During this course we have been told time and time again to watch out for null pointers and to take steps to catch them and what happens when we don’t - crashing being the main problem and I’ve had quite a few of those.

And in this lesson we are actually creating just that occurence. If we shoot the “enemy” pawn and kill it we are creating a nullptr because it has no APlayerController, yet no error is thrown and nothing of any kind occurs, not even a crash - and I can’t find figure out why - the lecturer says nothing about this.

So, what is occurring here to stop an error/crash from happening? As always here is a big thankyou in advance.

Regards.

Why would that be a problem?

I thought that nullptr’s were a bad thing, like crossing the streams, and they have a nasty habit of crashing Unreal (like a lot).

The following code has no issues

int* ptr = nullptr;
int* ptr2 = ptr;

Dereferencing a null pointer is where the demons lie. A null pointer is a pointer that doesn’t point anywhere anf dereferencing a pointer means to fetch the value at the address pointed to by the pointer.

Therefore trying to fetch the value at the address of nowhere == bad times.


nullptr itself is good. Otherwise why would it exist if it just blows things up just using it?

// 1.
int* ptr = new int(5);
int value = *ptr;

// 2.
delete ptr;

// 3
if (ptr != nullptr)
{
    int value = *ptr;
}
  1. This code creates an int on the heap with the value of 5 and the address of where that is stored is returned and stored in the variable ptr. The next line fetches the int at the address and stores it in a variable. Nothing wrong so far (basically just a setup for the next two points).

  2. delete ptr says to free that memory so the OS can reclaim that memory.

    ptr now points to invalid memory (not nullptr). Unless the compiler aided you here It’s the same address it stored previously but the OS has reclaimed that and can now overwrite that area of memory for its own use. Dereferencing this now is a big no no; you don’t know what’s there anymore.

  3. This check succeeds! Meaning you then dereference invalid memory :scream:. If the code set ptr to nullptr after deleting then there would be no issue.


In a nutshell nullptr :+1:, dereferencing nullptr :-1:

1 Like

We’re not worthy, we’re not worthy!!!

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

Privacy & Terms