Download

I wonder why it gets null pointer

TestWidget.h

class Something_API UTestWidget : public
{
	// 
	void Func();

	class ATComponent* OwningComponent;
	//
};

TestWidget.cpp

void UTestWidget::Func()
{
	if(OwningComponent != nullptr)
	{
		OwningComponent->DoSomething();
	}
}

TComponent.h

class Something_API ATComponent : public APlayerComponent
{
	//
	void BeginPlay() override;
	void DoSomething();
	class ATestWidget TheWidget;
	//
}

TComponent.cpp

void ATComponent::BeginPlay()
{
	//
	TheWidget = CreateWidget<UTestWidget>(UGameplayStatics::GetPlayerController(GetWorld(), 0), UTestWidget::StaticClass());
	
	if(TheWidget != nullptr){
	TheWidget->OwningComponent = this;
	}
	//
}

void ATComponent::DoSomething()
{
	GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("ATComponent::DoSomething("));
}

There was no problem in compilation. But after I access ATComponent::DoSomething through UTestWidget::Func(), Unreal Engine throws EXCEPTION_ACCESS_VIOLATION reading address 0x0000000000000000. Even I prevented the nullptr.
Is there any good solution to declare the pointer right or fix the bug?

Thank you for reading my trouble.

If you run it in Debugger, it will tell you what’s failing.

looks like something is not assigning well there…
try to debug TheWidget->OwningComponent, may it be nullptr…

1 Like

Thank you so much for your help.
I found out the cause. After i write UPROPERTY() on the raw pointer, there’s no more nullptr error.
I think the pointer is garbage-collected or destroyed by something like it.

1 Like