Search code examples
delphifiremonkeydelphi-xe6

Invalid Pointer Operation on dynamic array free


I'm pretty newbie to Delphi, so be kind please. I'm working on a software that allows users to customize its interface ( button's location, appearance, wtv) and some other stuff. The problem is, i have a grid and i store a representation of its cells on a dynamic array of Boolean which represents which cells are occupied. But when i try to free that matrix Sometimes i get an invalid pointer operation. Sometimes there isnt any error, but other times i get that invalid pointer stuff.

Definition:

type
  TMatrix = array of array of Boolean;

var
  Matrix: TMatrix;

Initialization:

SetLength(Matrix, MyGrid.ColumnCollection.Count, MyGrid.RowCollection.Count);

Usage: Mostly, these kind of operations are the only ones that i use with the matrix, and i'm sure that those variables col,row,colspan,rowspan never have values greater than the array boundary

//Checks if a set of cells are occupied
for i := column to (column + columnspan)-1 do
          begin
            for j := row to (row + rowspan)-1 do
            begin
              if Matrix[i, j] then
              begin
                valido := False;
              end;
            end;
          end;
     // if there isnt any cell occupied i can move a component to that location and i set the cells to true ( occupied)
    if (valido) then
          begin
              for i := column to (column + colspan)-1 do
                begin
                  for j := row to (row + rowspan)-1 do
                  begin
                    Matrix[i,j]:= True;
                  end;
                end;
          end

Free:

try
            begin
               SetLength(Matrix,0,0);
            end;
          except
            on E : Exception do
            begin
              //todo
              ShowMessage('Free: ' + E.Message);
            end;
          end;

I'm using FASTMM4 and i do get the memory leak warning, but i cant understand its contents..

What can possibly be causing this error? Im using Delphi Xe6 Firemonkey Any help will be appreciated. Thanks


Solution

  • The most likely explanation for this is that you are writing outside the bounds of the array. There's not enough code for us to be sure that is the case, but the symptoms you report are invariably caused by out-of-bounds access.

    Your next step is to get the compiler to write code that checks for our-of-bounds access. In your project options, in the compiler section, find the range checking option. Enable this option. Now the compiler will emit code that checks that your array indices are valid whenever you access the array. If your code fails the test, at runtime, an exception will be raised. This will make it blatantly obvious which part of your code is defective.