Delphi access violation error when assigning strings between record types

I have a simple post type. I assign a new instance of this record and use the procedure ("_clone") to copy the values ​​from the existing record to the new one. I get an access violation only when assigin is a string value.

Any ideas? Help is much appreciated.


TYPE Definition:

TPointer = ^TAccessoryItem;
TAccessoryItem = Record
  Id : Integer;
  PartNumber : String;
  Qty : Integer;
  Description : String;
  Previous : Pointer;
  Next : Pointer;
end;

Procedure TAccessoryList._clone (Var copy : TAccessoryItem; Var original : TAccessoryItem);

 begin

    copy.Id := original.Id;
    copy.Qty := original.Qty;
    copy.Partnumber := original.Partnumber;  **// Access errors happens here**
    copy.Next := Nil;
    copy.Previous := Nil;

  end;

Application call below:

  procedure TAccessoryList.AddItem(Var Item : TAccessoryItem);

 Var

    newItem : ptrAccessoryItem;

 begin

    GetMem(newItem, sizeOf(TAccessoryItem));

    _clone(newItem^, Item);

 end;
+5
source share
2 answers

You need to initialize the new structure with zeros. GetMem does not reset the allocated memory, so the fields in your record initially contain random garbage. You need to call

FillChar(newItem^, sizeof(TAccessoryItem), 0)

after GetMem before using the entry.

: , , RTL , ( ) , . , , , .

- , ... . , , . , AV , , , , , , .

, , , , , , , , .

Delphi - New():

New(newItem);

(sizeof, ), .

Dispose():

Dispose(newItem);

, , , , , .

FreeMem (newItem), , , , , .

, , ( "String", "string [10]" ), , , , , -, .

: GetMem/FreeMem . , . New Dispose "" , , , , .

, GetMem/FreeMem, , .

+20

( , tObject),

AccessoryItem1 := AccessoryItem2;

( AccessoryItem1 ^: = AccessoryItem2 ^, )

.

- , delphi , .

+2

All Articles