What's supposed to happen when using an object after FreeAndNil?

后端 未结 6 1867
轻奢々
轻奢々 2021-01-02 13:01

In my Delphi7 this code

var MStr: TMemoryStream;
...
FreeAndNil(MStr);
MStr.Size:=0; 

generates an AV: Access violation at address 0041D6D1

6条回答
  •  温柔的废话
    2021-01-02 13:18

    If you set a pointer to nil, you shouldn't be able to use it any more. But if you have another pointer to the same object, you can use it without getting an AV, because this pointer still points to the object address and not to nil.

    Moreover, freeing an object do not clear the memory used by the that object. It just marks it as not in use. Thats the reason you want get an AV. If the freed memory is allocated for another object, you will get a AV, because it no longer contains data that seems valid.

    FastMM4 has some settings that you can use while debugging, that will detect such conditions. From the FsatMM4Options.inc:

    {Set the following option to do extensive checking of all memory blocks. All blocks are padded with both a header and trailer that are used to verify the integrity of the heap. Freed blocks are also cleared to to ensure that they cannot be reused after being freed. This option slows down memory operations dramatically and should only be used to debug an application that is overwriting memory or reusing freed pointers. Setting this option automatically enables CheckHeapForCorruption and disables ASMVersion. Very important: If you enable this option your application will require the FastMM_FullDebugMode.dll library. If this library is not available you will get an error on startup.}
    {$define FullDebugMode}

    Another quote from the same file:

    FastMM always catches attempts to free the same memory block twice...

    As delphi uses FastMM from Delphi 2007 (2006 ?), you should get an error if you try to doublefree an object.

提交回复
热议问题