Delphi 3 memory allocation issue

Do I need to skip something pretty simple? I am trying to create a linked list in a Delphi 3 application.

This is implemented through the two classes ItemList and Item. ItemList is created when the form is created. It is saved for the life of form. Each object of the object is created if necessary. The form has an AddAcc function. AddAcc is called through the on-change event of one of the form controls.

What happens during this event:

  • AddAcc is called
  • AddAcc Create New Item Object
  • AccAdd calls ItemList.AddItem and passes the item by reference
  • AddItem puts the Item object at the tail of the list.

Ive checked AddItem and it works well. My problem is that every time * AddAcc * is called, it gets the same place in memory. Ive tried different ways to create a new Item object. Ive used New, GetMem (w / FillChar) and instantiated a local variable of type Item. All AddAcc calls result in the same memory.

Ive passed the Item object directly (by reference) to AddItem and, alternatively, passed a pointer to the Item object.

I thought that the link (pointer) to the instance of the Item object in the linked list would ensure that the memory location of the element was saved. However, it appears to be going after exit from the AddAcc class.

FUNCTION AddAcc; Var accItem : ptrItem; BEGIN GetMem(accItem, sizeOf(Item)); FillChar(accItem^, sizeof(Item), 0); ItemList.AddItem(accItem^); End; Procedure TItemList.AddItem(Var newItem : TAccessoryItem); begin Inc(_count); // add first item to the list If (_count = 1) Then begin _fifoHead := @newItem; _tail := @newItem; newItem.Next := @_tail; newItem.Previous := @_fifoHead; exit; end; _tail^.Next := @newItem; newItem.Previous := _tail^; mewItem.Next := @_tail; _tail := @newItem; end; 

Any help is greatly appreciated.

+4
source share
1 answer

Here is how I wrote a linked list:

 type PItem = ^TItem; TItem = record Next: PItem; Data: Integer; end; procedure Add(var First: PItem; Data: Integer); var NewItem: PItem; begin New(NewItem); NewItem.Next := First; NewItem.Data := Data; First := NewItem; end; ... var First: PItem; begin First := nil; Add(First, 42); //etc. end; 

When you need to free your list, you do the following:

 var Item: PItem; begin while Assigned(First) do begin Item := First; First := Item.Next; Dispose(Item); end; end; 

I believe this is the canonical way of writing code like linked lists in Pascal.

I intentionally wrote this code for this simplest linked list you could imagine. This allows you to focus on distributing, using pointers, etc. You seem to already know how to maintain links in your more complex list, and so I think it’s easy for you to adapt this style of code to your needs.

+1
source

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


All Articles