开发者

getmem memory leak, delphi

I am trying to run a old midi component in Delphi, and it works for the most part of it, but if I try loading 2 files in a row, it crashes.

some research led me to install EurekaLog, which point to memory leaks in the co开发者_运维技巧de.yay!

I'm not very good with memory pointers stuff, but this code down is highlighted by Eureka here got me thinking, maybe there is a bug with memory not being freed??

I tried adding FreeMem at the end of it, but it doesn't work?

function TMidifile.ReadString(F: integer): string;
var
  s: PChar;
  i: integer;
begin
  GetMem(s, F + 1);
  s[F] := chr(0);
  for i := 0 to F - 1 do
  begin
    s[i] := Chr(chunkIndex^);
    inc(chunkIndex);
  end;
  result := string(s);
end;


Kornel's got the right idea. You could probably simplify it even further, like so:

function TMidifile.ReadString(F: integer): AnsiString; 
begin
  SetLength(Result, F);
  Move(ChunkIndex^, result[1], F);
  inc(chuncIndex, F);
end;

This will make reading a lot faster, especially if you're using the Fastcode version of Move (or a recent version of Delphi that comes with the Fastcode version built into the RTL.)


You can't typecast to an AnsiString, for they are reference counted.

Wouldn't this be easier?

function TMidifile.ReadString(F: integer): string; 
var i: integer; 
begin
  SetLength(Result, F);  
  for i := 1 to F do 
  begin 
    Result[i] := Chr(chunkIndex^); 
    inc(chunkIndex); 
  end; 
end;


The problem is that you can't take a bunch of random bytes and cast it as a string. string has a specific structure, and allocation is managed by the compiler.

I could rewrite this bit for you, but I don't think I'd be doing you any favors, since I must presume that the code which is calling this is not doing any better in terms of memory management.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜