VCLの別フォームでGetComputerNameを呼び出すとAccessViolationが発生する

提供: Support
移動先: 案内検索

問題

例えば、フォーム1からフォーム2を開き、フォーム2でWindows APIのGetComputerNameを呼び出してコンピュータ名を取得し、フォーム2上のLabelにコンピュータ名を表示するプログラムを作成しています。

procedure TForm1.Button1Click(Sender: TObject);
begin
   Form2.ShowModal;
end;
procedure TForm2.FormShow(Sender: TObject);
var
  lpBuffer: PWideChar;
  nSize: Cardinal;
begin
  nSize := MAX_COMPUTERNAME_LENGTH + 1;
  GetMem(lpBuffer, nSize);
  try
    if GetComputerName(lpBuffer, nSize) then
      Label1.Caption:=lpBuffer
    else
      Label1.Caption:='';
  finally
    FreeMem(lpBuffer);
  end;
end;

このプログラムを実行すると、Access Violationが発生します。このエラーを解決するためにはどうすれば良いですか?

解決

Windows APIのGetComputerNameを呼び出す場合、GetMem関数でなく、StrAlloc関数でバッファを確保してください。

procedure TForm2.FormShow(Sender: TObject);
var
  lpBuffer: PWideChar;
  nSize: Cardinal;
begin
  nSize := MAX_COMPUTERNAME_LENGTH + 1;
  lpBuffer := WideStrAlloc(nSize);
  try
    if GetComputerName(lpBuffer, nSize) then
      Label1.Caption := lpBuffer
    else
      Label1.Caption := '';
  finally
    strDispose(lpBuffer);
  end;
end;