Delphi 7 refpount error when copying a record to dynamically allocated memory

I came across a strange behavior in Delphi when assigning a variable type of a write-controlled string field variable to a dynamically allocated buffer. What is wrong with him and how can I fix it?

type
  PRec = ^TRec;
  TRec = packed record
    Foo: integer;
    Bar: string;
  end;

procedure Error;
var
  P, Q: PRec;
  R, T: TRec;
begin
  R.Foo := 1;
  R.Bar := 'Bar';
  T := R; // Ready
  Q := @T;
  Q^ := R; // Ready
  GetMem(P, SizeOf(TRec));
  P^ := R; // Access violation in _LStrAsg at 
           // "MOV     ECX,[EDX-skew].StrRec.refCnt"

  R := P^; // Just to keep reference while debugging
end;
+4
source share
1 answer

Your entry is a managed entry. Therefore, it must be initialized. Your code uses GetMemone that does not initialize the record. You should use instead New. Replace

GetMem(P, SizeOf(TRec));

from

New(P);

Similarly, when you need to free yourself, you must complete the recording. Use Dispose, not FreeMem.

, - . :

// allocate and initialize
GetMem(P, SizeOf(P^));
Initialize(P^);

// finalize and deallocate
Finalize(P^);
FreeMem(P);
+6

Source: https://habr.com/ru/post/1616569/


All Articles