[fpc-devel] GetMem(SomePointer, 0) <> nil

Jonas Maebe jonas.maebe at elis.ugent.be
Tue Mar 1 13:29:00 CET 2011


On 01 Mar 2011, at 07:32, Paul Ishenin wrote:

> I noticed today that if I want to allocate 0 bytes I get not a nil  
> but a valid pointer. Why?

The current code that causes this comes from this (cvs) revision:

revision 1.16
date: 1999-09-17 19:14:12 +0200;  author: peter;  state: Exp;  lines:  
+284 -966;
   + new heap manager supporting delphi freemem(pointer)

I guess the reason was to be able to
a) give a run time error if someone tries to do freemem(nil)
b) nevertheless allow freeing all pointers that have been allocated  
using getmem() (even if the size was 0 bytes), for backwards  
compatibility with FPC code from before that revision (FPC also  
returned a non-nil pointer in that case)

> This is incompatible with delphi.

If it is changed, it will also require changes in cmem (and probably  
also in heaptrc), because at least on Mac OS X libc also returns a  
valid pointer for malloc(0).

> And I suppose cause crashes and memory leaks not only in my delphi  
> code which I'm porting to FPC/Lazarus.

That sounds very much like badly written code.


Jonas



More information about the fpc-devel mailing list