开发者

Will this cause a memory leak in Delphi?

In an attempt to开发者_JAVA技巧 get just a filename:

procedure TSomeClass.GetFileName(AData : string) : string;
var
  p : pchar;
begin

  p := pchar(AData);
  while not (p^ in ['/', '&', '#', ':']) do
    inc(p);

  result := p;

end;


There is no memory leak there. Your pointer p points to a block of memory that is owned by the string AData and so you do not need to free p. The string class manages all allocation and deallocation for you.

What can happen though is that if the string does not contain at least one of those 4 characters your loop will run off the end and eventually raise an access violation. You should consider terminating the loop when it reaches a null terminator.

It's just simpler to avoid pointers altogether:

function TSomeClass.GetFileName(const AData: string): string;
var
  i, len: Integer;
begin
  len := Length(AData);
  for i := 1 to len do
    if AData[i] in ['/', '&', '#', ':'] then begin
      Result := Copy(AData, i, len);
      exit;
    end;
  Result := '';
end;

The replicates the logic of your code, and removes the risk of access violations. However, your code was returning the portion of the string starting from, and including, the first instance of /, &, # or :. Is that really what you wanted?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜