FastMM4 and detection of memory corruption

by Radek Červinka 15. February 2011 22:17

FastMM can be used for detect of memory corruption. As first step please enable FullDebugMode in fastmm .inc file (there is line for this).

In this case our memory manager will mark every allocated memory block with checksum (at the begin and at the end too) and this checksum will be checked on every operation (like reallocation or during free).

There is another possibility: if we want harder check, FastMM can check all block during every operation - but this is really slow and for me is not necessary.

Small example: allocation of dynamic array of 10 bytes and fill this array with 11 bytes of value 23 (17h) - e.g. 1 byte more. See screenshot - there are 11 bytes in list and word "footer" is sign of corruption after our block.

    1program Project1;
    2{$APPTYPE CONSOLE}
    3uses
    4  FastMM4,
    5  SysUtils, Classes;
    6var
    7  ai: array of byte;
    8begin
    9//there is FullDebugModeScanMemoryPoolBeforeEveryOperation := True;
   10// but it is very slow
   11    SetLength(ai, 10);
   12    FillChar(ai[0], 11, 23);
   13    writeln(ai[0]);
   14    SetLength(ai, 5); // FastMM (fulldebugmode) detect problem here
   15    finalize(ai);
   16end.

When FastMM is compiled with fulldebug mode, program show this message on line 14 (without reallocation /SetLength/ FastMM display message on block free or on application terminate).

realloc FastMM4

When FastMM_FullDebugMode.dll is available, program show this more juicy output:

realloc FastMM4 FastMM_FullDebugMode.dll

Programmer now know where is original allocation (Q:\boundary\Project1.dpr - line 10) and where is error (Q:\boundary\Project1.dpr - line 13).

And finally exception EOutOfMemory is raised as result of problem detection and abort of action.

EOutOfMemory

Original memory manager (up to Delphi 2006) or FastMM without fulldebug mode don't check memory corruption. FastMM without this mode use optimized function and similar validity check will slow down application.

Tags: ,

Practices

Comments are closed