Link to home
Start Free TrialLog in
Avatar of Stef Merlijn
Stef MerlijnFlag for Netherlands

asked on

Return windows user in Delphi XE2

Following function should return the username of the currently logged in Windows user.
But when executing this code in Delphi XE2 I get a Memory Overrun leak error at line:
FreeMem(PC);

How should the code be corrected?
The function must work with Windows XP, Vista, 7 and 8
And on Delphi XE2 32bit and 64bit.

function ReturnUser:String;
var
  PC: PChar;
  Car: Cardinal;
begin
  Car := 0;
  PC := Nil;
  GetUserName(PC,Car);
  If Car <> 0 then
  begin
    GetMem(PC,Car);
    GetUserName(PC,Car);
    Result := String(PC);
    FreeMem(PC);
  end else
    Result := 'UNKNOWN';
end;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Thommy
Thommy
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Stef Merlijn

ASKER

Works perfectly, thank you.