Search code examples
delphiwinapidelphi-10.1-berlindelphi-10.2-tokyo

Reproducible error with Winapi.ShlObj.SHGetFolderPath


With this code I get an AV:

uses
  Winapi.ShlObj;

function GetUserAppDataPath: string;
var
  ThisPath: PWideChar;
begin
  if Winapi.ShlObj.SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, ThisPath) = S_OK then
    Result := string(ThisPath)
  else
    Result := '';
end;

enter image description here

In Delphi 10.2 Tokyo, if I call this function twice, the second time I get an AV.

What causes this error?

I used PWideChar because of the Delphi IDE told me so: enter image description here


Solution

  • You aren't following the protocol laid out by the documentation. The documentation for the final argument says

    A pointer to a null-terminated string of length MAX_PATH which will receive the path.

    You need to allocate that buffer and pass its address.

    function GetUserAppDataPath: string;
    var
      ThisPath: array[0..MAX_PATH-1] of Char;
    begin
      if Winapi.ShlObj.SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, ThisPath) = S_OK then
        Result := ThisPath
      else
        Result := '';
    end;