Consider the following code:
procedure Test;
var
MyPCharArray: array of PChar;
begin
SetLength(MyPCharArray, 3);
GetMem(MyPCharArray[0], 5);
GetMem(MyPCharArray[1], 5);
GetMem(MyPCharArray[2], 5);
StrCopy(MyPCharArray[0], 'test');
StrCopy(MyPCharArray[1], 'abcd');
StrCopy(MyPCharArray[2], '1234');
// Are these necessary?
FreeMem(MyPCharArray[0], 5);
FreeMem(MyPCharArray[1], 5);
FreeMem(MyPCharArray[2], 5);
end;
Should the allocated elements be freed manually, or the compiler will free the array elements automatically when MyPCharArray goes out of scope?
Indeed each of your calls to GetMem must be matched with a call to FreeMem.
I’m not sure why you have this array. It’s not a type that I’d expect to see in pure Pascal code. So my guess is that you are passing the PChar array to some external library. In which case I’d declare an array of string as well as the array of PChar. And then make each PChar element by using PChar(…) on the corresponding element of the string array. Then you can avoid the StrCopy, GetMem and FreeMem.