0
0

【UE5】今さらUnrealC++のTArray「Insert」の範囲外アクセスの挙動を見てみる 4日目

Posted at

0.最初

配列の長さより大きい所にInsertを行うとどのような挙動をするのか気になりました
テストBPは以下の感じ
・長さ3の配列
・100番目に文字列「DDD」を追加

スクリーンショット 2024-07-04 233043.png

以下の2点のどちらかが行われるだろうと予想しました
・指定したIndexの差分だけResizeされる
 →長さ3の時Insertで100番目に追加する時、97個分の配列が確保される

・「配列の長さ分の場所に追加できません」的なエラーが表示され動作停止する

1.結果

以下のワーニングが表示され「Insert」ノードがスキップされました

スクリーンショット 2024-07-04 234659.png
Script Msg: Attempted to insert an item into array StrArray out of bounds [100/2]!
配列に項目を挿入しようとしました

デバッグ文
スクリーンショット 2024-07-04 234605.png

2.解説

UKismetArrayLibrary 204行目
長さより大きいIndexを入力するとこの処理がスキップされます

void UKismetArrayLibrary::GenericArray_Insert(void* TargetArray, const FArrayProperty* ArrayProp, const void* NewItem, int32 Index)
{
	if( TargetArray )
	{
		FScriptArrayHelper ArrayHelper(ArrayProp, TargetArray);
		FProperty* InnerProp = ArrayProp->Inner;

		if (ArrayHelper.IsValidIndex(Index)||(Index >= 0 && Index <= ArrayHelper.Num()) )
		{
			ArrayHelper.InsertValues(Index, 1);
			InnerProp->CopySingleValueToScriptVM(ArrayHelper.GetRawPtr(Index), NewItem);
		}
		else
		{
			FFrame::KismetExecutionMessage(*FString::Printf(TEXT("Attempted to insert an item into array %s out of bounds [%d/%d]!"), *ArrayProp->GetName(), Index, GetLastIndex(ArrayHelper)), ELogVerbosity::Warning, InsertOutOfBoundsWarning);
		}
	}
}

3.結論

結論としては「ノードスキップ」でした
勝手にResizeされるだろうと思っていましたが
ミスした場合多くのメモリを消費されるのでよく考えればそんなこと無いなと思いましたね

4.参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0