Newsgroups : Borland : borland.public.delphi.nativeapi.win32 : 2007 Oct : PWideChar - allocating.free-ing memory

www.cryer.info
Managed Newsgroup Archive

PWideChar - allocating.free-ing memory

Subject:PWideChar - allocating.free-ing memory
Posted by:"Alf Beford" (..@home.com)
Date:Fri, 26 Oct 2007 14:04:07

Hello

I'm passing a dynamic array to a WinAPI function - each array element is a record with two fields - the first field is an Integer,
the second is a PWideChar. Separately I have an array of Strings, I size my dynamic array to match the length of the String array,
then I copy each String into a PWideChar field, as below (I've changed the array names to make this clearer - hopefully):

var
  Lo, Hi, i, LenW: Integer;

...

    Lo := Low(StringArray);
    Hi := High(StringArray);
    // Set the dynamic array length to match the String array length
    SetLength(Int_PWideChar_Array, Length(StringArray));
    for i := Lo to Hi do begin
      Int_PWideChar_Array[i].IntegerField := SomeNumber;
      // Get the length of the String array element, then double for equiv WideString + 1 for #0
      WLen := Length(StringArray[i]) * 2 + 1;
      // Allocate memory for the PWideChar
      Int_PWideChar_Array[i].pszText := AllocMem(WLen);
      StringToWideChar(StringArray[i], Int_PWideChar_Array[i].pszText, WLen);
    end;

This works as expected, and the WinAPI function call operates correctly. I've seen various messages that suggest you can do things
like:

    for i := Lo to Hi do begin
      Int_PWideChar_Array[i].IntegerField := SomeNumber;
      Int_PWideChar_Array[i].pszText := PWideChar(WideString(StringArray[i]));
    end;

...but that seems to produce odd results (the first Int_PWideChar_Array element 'pszText' value always seems to get overwritten with
the last). My question, then, is - since I use AllocMem, shouldn't I need to call FreeMem/Dispose?

I only ask because at the moment I don't, and FastMM doesn't mention any leaks. If I add FreeMem or Dispose after the WinAPI call
has completed, FastMM complains about corrupted memory:

for i := Lo to Hi do
  Dispose(Int_PWideChar_Array[i].pszText);

I'd be very grateful if someone could clarify this for me - many thanks in advance.

Replies:

www.cryer.info
Managed Newsgroup Archive