# Why is this function crashing unreal?

**URL:** <https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466>\
**Category:** Programming & Scripting\
**Tags:** unreal-engine\
**Created:** [June 20, 2015, 4:03pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466 "2015-06-20T16:03:33Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 4:03pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/1 "2015-06-20T16:03:33Z")

</div>

Every time I run this, Unreal unceremoniously crashes. FEventPublisherEvent is a dynamic multicast delegate, so my assumption is that eventStorage[hashID] is empty, but I was under the impression that running eventStorage.Find() would ensure that the tkey wasn’t referring to an empty value, and that multicast\_delegate.Broadcast(): was harmless if the delegate was unassigned.

```
TMap<FString, FEventPublisherEvent> eventStorage;

bool UEventPublisher::PublishEvent(FString hashID){
	if (eventStorage.Find(hashID)){
	eventStorage[hashID].Broadcast(); 
	return true;
	}
	else{
		return false;			
	}
}
```

---

<div class="post-metadata">

**Author:** ![twiddle](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@twiddle](https://forums.unrealengine.com/u/twiddle)\
**Post date:** [June 20, 2015, 5:16pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/2 "2015-06-20T17:16:46Z")

</div>

From the documentation:

```
The function bound to a delegate is
executed by calling the delegate's
`Execute()` function. You must check
if delegates are "bound" before
executing them. [...] if the object
gets destroyed out from underneath the
delegate, you will be able to handle
these cases by calling `IsBound()` or
`ExecuteIfBound()` functions

```

To confirm that this is really what’s causing your crash though, I’d use the debugger in your development environnment. Place a breakpoint at the start of the function and step the code (using f10 if you are using VS) and see which line causes the crash. Without actually debugging we are guessing at the cause.

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 6:24pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/3 "2015-06-20T18:24:38Z")

</div>

So I feel really silly, I don’t think it’s code inside the event publisher at all (although for the record, isn’t Broadcast() the correct function, not Execute(), when it’s a multicast delegate that has multiple methods bound to it?)- it looks like eventPublisher, my reference to the component with all this code, isn’t getting set correctly, so all the calls are going to an uninitialized pointer.

I can make sure that it doesn’t crash by always prefacing calls to eventPublisher with if (eventPublisher), but do you have any idea what’s wrong with the way I’m retaining a reference to the component? eventPublisher is supposed to a pointer to the class UEventPublisher, which is an ActorComponent attached to the root character. I’m retaining it at runtime with:

UEventPublisher\* eventPublisher = Cast(this-\>GetComponentByClass(UEventPublisher::StaticClass()));

But it’s apparently not finding it, because eventPublisher always remains null.

---

<div class="post-metadata">

**Author:** ![tenowg](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@tenowg](https://forums.unrealengine.com/u/tenowg)\
**Post date:** [June 20, 2015, 7:56pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/4 "2015-06-20T19:56:16Z")

</div>

Just out of curiosity (without seeing your code). If UEventPublisher is attached “this” why not just keep a reference or pointer assigned to a variable (assigned when you create/attach the component to the actor), and use that reference instead of searching for it?

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 8:01pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/5 "2015-06-20T20:01:33Z")

</div>

I think that’s what I should do, I’m a fairly recent Unity refugee, so I’m still learning UE’s environment- would you mind expanding on the exact syntax to create the default class in the first place? If it were C#, I would do something like:

UEventPublisher publisherInstance = new UEventPublisher;  
publisherPtr\* = &publisherInstance;

---

<div class="post-metadata">

**Author:** ![twiddle](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@twiddle](https://forums.unrealengine.com/u/twiddle)\
**Post date:** [June 20, 2015, 8:17pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/6 "2015-06-20T20:17:39Z")

</div>

Fair point about Execute vs Broadcast, I was just fumbling for something that spoke explicitly about the need to check if the event was bound before you called it.

This sounds like a garbage collection issue. Tenowg has the right idea I reckon. Try marking EventPublisher variable as UPROPERTY and declaring it in your class as a member, then initialising it during your class constructor. UPROPERTYs guarantee that your component is considered to be referenced and wont be GC’d out from under you.

Oh, just to point out given you’re a recent convert from unity - use EventPublisher = new EventPublisher() rather than declaring a local instance of the item and assigning it.  
When you use new, you create the object on the ‘heap’ and its memory remains allocated until you ‘delete’ the pointer. If you do what you proposed, you’re creating a ‘stack’ variable and your pointer will only be valid in the function that you created the variable because after your function exits the stack is ‘torn down’ and your pointer will dangle (ie point to garbage).

---

<div class="post-metadata">

**Author:** ![tenowg](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@tenowg](https://forums.unrealengine.com/u/tenowg)\
**Post date:** [June 20, 2015, 8:27pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/7 "2015-06-20T20:27:46Z")

</div>

Avoid using new keyword, use Unreal functions instead:  
new UEventPublisher would be, `NewObject<UEventPublisher>()` to just create a new object, or to create and attach a new Component read on.

Here is an example of how I set default objects in my constructor:

My BaseBuildingActor.cpp

```
// Sets default values (This is basic default constructor, NOTE no FObjectInitializer is needed)
ABaseBuildingActor::ABaseBuildingActor()
{
	// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

	StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Static Mesh"));
	RootComponent = StaticMeshComponent;

    // CreateDefaultSubobejct will create and register the component and return
    // A pointer to the created Component
    SomeOtherComponent = CreateDefaultSubobject<UOtherComponent>(TEXT("OtherComponent"));
       SomeOtherComponent->AttachTo(RootComponent);
}

```

In My BaseBuildingActor.h

```
// Components
UPROPERTY(VisibleAnywhere, Category = StaticMesh)
UStaticMeshComponent* StaticMeshComponent;

UPROPERTY(VisibleAnywhere, Category = OtherCategory)
UOtherComponent* SomeOtherComponent;

public:
    // Just some simple getters for my private values.
	FORCEINLINE class UStaticMeshComponent* GetBuildingMeshComponent() { return StaticMeshComponent; }
    FORCEINLINE class UOtherComponent* GetSomeOtherComponent() { return SomeOtherComponent; }
```

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 8:34pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/8 "2015-06-20T20:34:53Z")

</div>

Okay, so let me be boringly thorough, as I’m pretty sure the root of the problem is me doing something syntactically odd out of inexperience: my root character class is AAvatar, which extends ACharacter. In Aavatar.h, I have my declarations:

```
UEventPublisher ePublisherComponent; 
UEventPublisher* eventPublisher; 

```

Then in the .cpp, I define them in the constructor:

```
AAvatar::AAvatar()
{
 	// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;
	OnActorBeginOverlap.AddDynamic(this, &AAvatar::OnOverlapBegin); //Set up delegate for components to hook into

	ePublisherComponent = new UEventPublisher();
	eventPublisher = &ePublisherComponent;
}

```

I’m pretty sure that’s right, but I get an error for the new UEventPublisher line, “no operator “=” matches these operands, types are UEventPublisher = UEventPublisher\*”. I’m pretty certain that ePublisherComponent isn’t a pointer type though, as I declared it to be an eventpublisher.

---

<div class="post-metadata">

**Author:** ![twiddle](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@twiddle](https://forums.unrealengine.com/u/twiddle)\
**Post date:** [June 20, 2015, 8:36pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/9 "2015-06-20T20:36:53Z")

</div>

UPROPERTY variables that point to subcomponents are declared as ComponentType \* , ie pointers. You should remove ePublisherComponent, and just have the pointer variable eventPublisher = new UEventPublisher()

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 9:22pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/10 "2015-06-20T21:22:54Z")

</div>

Okay, that was really weird. When I initially implemented this, I accidentally initialized eventPublisher in the header instead of the class constructor, and it not only crashed the project, it actually made it incapable of loading again- UE died the instant I tried to open it.

Instead of rolling back to this morning’s backup I made a brand-new project, so we can be 100% sure nothing weird is interacting with the bug. The only original code is my EventPublisher class, which I brought over, and two lines added to the MyTestProjectCharacter. class:

.h:

class ACodeProjectCharacter : public ACharacter  
{  
GENERATED\_BODY()

```
	UPROPERTY(VisibleAnywhere)
	UEventPublisher* eventPublisher;
//Lots of default engine code follows

```

}

.cpp:

```
ACodeProjectCharacter::ACodeProjectCharacter()
{
	//Intialize event publisher
	eventPublisher = NewObject<UEventPublisher>();
	//Engine stuff comes after this
}

```

eventPublisher is a UPROPERTY now, so it shouldn’t be GCed, but when I compile and run, it’s value is listed as empty on the character, and the debug message I put in UEventPublisher-\>BeginPlay() never fires.

---

<div class="post-metadata">

**Author:** ![tenowg](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@tenowg](https://forums.unrealengine.com/u/tenowg)\
**Post date:** [June 20, 2015, 9:23pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/11 "2015-06-20T21:23:00Z")

</div>

Just to point out, so others notice this, Execute needs to be checked before execution (this would point to a normal, single type delegate) but as far as I know, it is always safe to Broadcast from a multi/event delegate (these two being inherently the same)

---

<div class="post-metadata">

**Author:** ![tenowg](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@tenowg](https://forums.unrealengine.com/u/tenowg)\
**Post date:** [June 20, 2015, 9:26pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/12 "2015-06-20T21:26:34Z")

</div>

Change:

```
UEventPublisher ePublisherComponent; 
UEventPublisher* eventPublisher;

```

To:

```
UPROPERTY()
UEventPublisher* EventPublisher;

```

Then, use CreateDefaultSubobject to create the component, this will register the component, so it can do any ticks, and or interact with the world instead of just creating the NEW object, if this isn’t a concern you can use the new keyword.

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 9:57pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/13 "2015-06-20T21:57:12Z")

</div>

Okay, so weirdness continues- based on tenowg’s suggestion I tried CreateDefaultSubobject, that actually made a component that stuck around, but looking at my character class in the editor, Event Publisher still reads “None”.

if (EventPublisher != NULL) evaluates to true, so the component’s obviously where it’s supposed to be, so I’m going to try plugging the rest of my event system back in to see if I can reproduce the original crash.

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 20, 2015, 10:07pm UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/14 "2015-06-20T22:07:07Z")

</div>

Sorry for the flurry of comments, but I’m convinced I’m using the wrong method to verify that the pointer has a target- if (pointer) resolves to true if the pointer’s looking at something, and false if it’s hanging, right? Because I’m looking right at my EventPublisher component in the editor window, but the following code always gives me the “No publisher” debug message:

```
void ACodeProjectCharacter::PublisherTest(){

	if (EventPublisher!= NULL){
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Event Publisher found- publishing to event publisher"));
		EventPublisher->PublishEvent("Attack");
	}
	else{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("No event publisher- could not complete operation"));
	}

```

}

---

<div class="post-metadata">

**Author:** ![HInoue](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@HInoue](https://forums.unrealengine.com/u/HInoue)\
**Post date:** [June 21, 2015, 6:04am UTC](https://forums.unrealengine.com/t/why-is-this-function-crashing-unreal/322466/15 "2015-06-21T06:04:57Z")

</div>

I still have some outstanding weirdness, but this was a massive help, and helped fix well over half of the problems I’ve been having with this… _huge_ thank you for your time and patience 🙂
