Skip to content

Array management by pointer

Now imagine that a pointer eliminated from array with classical deletion is used by any software: yours again, an other, or system.
If it will be used as pointer again, any change to it will directly affect the memory location related to your software.

You'll get undesired changes, very dangerous ones, because of a Troy's Horse you accidentally give away.
So, just like you create a link to variable with a pointer, you simply need to destroy this link (then eventually you can delete the variable)

procedure TForm1.deleteEmployee(id:integer);
var i,k,imax,deletepoint :integer;


  for i:=0 to imax do begin
    if self.EmployeeArray[i]^.id = id then begin
      if deletepoint < imax then begin
         dispose(self.EmployeeArray[deletepoint]); //FREE the created pointer
         for k:=deletepoint+1 to imax do begin
         SetLength(self.EmployeeArray, imax);
      end else begin //deletepoint = imax
        dispose(self.EmployeeArray[imax]); //FREE the created pointer
        SetLength(self.EmployeeArray, imax);


Dispose is the procedure to remove the link and to free pointer: after that the pointer doesn't exist anymore (logically).
With dispose executed you can reorder array in any way you desire, without any danger.

In particular we see here that if the pointer to be disposed is in the middle of array, then we after move items to prior positions (from k to k-1) and then we assign nil to last pointer, which formally doesn't belong to array anymore, but still lives.

nil is not the same of dispose application; simply pointer points to nothing, but still exists.

Same situation if pointer to be disposed is the last: here we assign the nil value.

Is it a dangerous case?

No, but only thanks to SetLenght, which rewrites the boundaries of array, and it destroys every item remained out too: so we make the same of dispose.

[If SetLength makes range bigger, then it automatically creates variables of type that array hosts]