简体   繁体   English

将记录复制到动态分配的内存时,Delphi 7引用计数错误

[英]Delphi 7 refcount error when copying a record to dynamically allocated memory

I faced a strange behavior in Delphi when assigning a record type variable with a managed string field to a dynamically allocated buffer. 在将带有托管字符串字段的记录类型变量分配给动态分配的缓冲区时,我在Delphi中遇到了一种奇怪的行为。 What's wrong with it and how could be corrected? 这有什么问题,如何纠正?

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;

Your record is a managed record. 您的记录是托管记录。 As such, it needs to be initialized. 因此,它需要初始化。 Your code uses GetMem which does not initialize the record. 您的代码使用GetMem ,它不会初始化记录。 Instead you should use New . 相反,你应该使用New Replace 更换

GetMem(P, SizeOf(TRec));

with

New(P);

Likewise when you need to deallocate, you must finalize the record. 同样,当您需要解除分配时,您必须完成记录。 Use Dispose rather than FreeMem . 使用Dispose而不是FreeMem

It is possible to initialize and finalize manually if, for some reason, you need to do that. 如果出于某种原因需要这样做,则可以手动初始化和完成。 That would look like this: 这看起来像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM