TArray - Issues with adding.


Trying to get my C++ skills back in shape and I’m following a book that was written for 4.5 I believe.

So I have to convert some of the code to current and I’m currently having issues with the TArray…

Whenever I try to add to the Array I get an “Access violation reading location”-Error.

I’ve tried googling around to find an answer but I just cant seem to find an answer that works for me.

I have the following HUD class, where I also create a “message” struct for messages that other NPC’s can send to the player when they enter their proximity.

struct FMessage

	FString message;

	float time;

	FColor color;

		message = "";
		time = 5.f;
		color = FColor::White;

	FMessage(const FMessage& cop)
		message = cop.message;
		time = cop.time;
		color = cop.color;

	FMessage(FString iMessage, float iTime, FColor iColor)
		message = iMessage;
		time = iTime;
		color = iColor;



	AMyHUD(const FObjectInitializer& ObjectInitializer);

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = HUDFont)
	UFont * hudFont;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Message")
	TArray<FMessage> messages;

	virtual void BeginPlay() override; // nevermind this

	virtual void DrawHUD() override;
	void DrawMessages();
	void AddMessage(FMessage msg);


As you can see above there is an TArray holding FMessages. Nothing special as far as I’m aware.

Whenever my collision function calls the AddMessage function for the HUD, the application directly crashes.

AddMessage looks as following:

void AMyHUD::AddMessage(FMessage msg)

Now I’ve tried to have the struct as just a struct and not make it a USTRUCT, but the results where the same.
I’ve tried without any form of constructors in the struct and still the same problem.
In the constructor of the HUD i’ve added a init to the messages array set to 50 just to test and its still the same.

What could be the issue here?

Thank you.

Best wishes

When you say Access violation error you mean Visual Studio reports this error and the editor crashes, right? Can you tell us which line that happens? I suspect it does not have to do with AddMessage itself since arrays and structs auto-initialize and can’t be NULL.

Hmm, so I think I found the fault for this error.

I was not using MyHUD… it was using the default HUD. So of course there was no memory reserved over there.

Sorry any confusion. Get a Malloc crash now instead when changing HUD, but I’m going forward again at least. Thank you!