LoginSignup
0
1

More than 5 years have passed since last update.

C++ Builder XE4, 10.2 Tokyo > NULLに対して.IsEmpty()を使うのは良くない | Indy: IdUDPClient1->ReceiveString()の戻り値がNULLの場合がある

Last updated at Posted at 2017-11-24
動作環境
C++ Builder XE4
RAD Studio 10.2 Tokyo Update 2 (追記: 2018/01/05)

関連

Error

Access violation at address XXXX in module 'プログラム名.exe' 読み取り of address XXXXXXXX.

上記のエラー原因を特定して、コードを見ると以下の状況だと分かった。
(コードは簡素化している)

    String wrk = NULL;

    if (wrk == NULL) {
        ShowMessage(L"NULL1");
    }
    if (wrk.IsEmpty()) {
        ShowMessage(L"NULL2");
    } else {
        ShowMessage(L"something");
    }

上記の結果は以下となる。

  • NULL1が表示される
  • somethingが表示される

実コードにおいて、wrkはUDPからの受信を受ける。
特定条件においてwrkにNULLが入り、.IsEmpty()でない時の処理を実行して、Access violationが発生しているようだ。

code > Indy使用

Unit1.cpp
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
    _di_IIdTextEncoding m_enqSJIS = IndyTextEncoding(932);

    String cmd = L"zabuuun!";

    IdUDPClient1->Host = L"192.168.0.79";
    IdUDPClient1->Send(cmd, m_enqSJIS);
    String res = IdUDPClient1->ReceiveString(1000, m_enqSJIS); // msec

    // ここでresはNULLになる
}
//---------------------------------------------------------------------------

上記の処理で相手先がいない場合、resはNULLが入ることを確認した。
resに対して.IsEmpty()を使うのは良くないだろう。

関連: C++ Builder > 無効なポインタ操作 > 不定値でのFree()によるメモリ破壊 > その後の処理で「無効なポインタ操作」 | Free()でなくdeleteを使う | ヌルポインタ経由でのメンバ関数呼び出しはC++の仕様上は未定義の挙動

コード変更

.IsEmpty()を使う処理の前にNULLチェックを入れることで,
「Access violation at address」エラーは出なくなった。

0
1
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
1