[U-Boot] [PATCH] Prevent malloc with size 0

Mike Frysinger vapier at gentoo.org
Fri Oct 22 09:20:22 CEST 2010


On Friday, October 22, 2010 02:10:16 Joakim Tjernlund wrote:
> Mike Frysinger wrote on 2010/10/21 21:51:53:
> > it is useful for malloc(0) == NULL.  the glibc behavior is downright
> > obnoxious.  we disable this for uClibc and dont see problems.  if
> > anything, we catch accidental programming mistakes which then get fixed.
> 
> There is a value in having the possibility to express a
> 0 bytes data set. Consider this simple example:
> An app read lines from a file and mallocs each line read and builds an
> array with malloced pointers. The last entry is a NULL ptr to
> signal EOF. This breaks down for empty lines if malloc(0)
> returns NULL.

i dont think so ... C strings are always at least one byte, so an empty line 
would be malloc(1)

> Not to mention error handling, as I recall, a malloc(0) that returns NULL
> does not set errno which screws error handling. One have to bend over
> just to cope with this.

that depends on your implementation.  in u-boot, there really is no "errno" 
concept.  but i dont see how this matters as i dont see any example in u-boot 
context where malloc(0) is a problem.

> > why exactly do you want malloc(0) to return valid memory ?  i would
> > rather have u-boot return an error.
> 
> Ideally it should return a ptr to invalid memory so you get a SEGV if you
> try to defer the ptr but I take anything over a NULL ptr.

the concept of an invalid pointer is pretty arch-specific.  and it changes the 
semantics of what the vast majority of coders (and their code) out there 
expect -- NULL means error while non-NULL means success.

a better question might be "why isnt a NULL pointer on your platform an 
invalid pointer" ?  ive added a simple CONFIG define for Blackfin users to do 
just that -- make access to the low 1KiB of memory generate an exception.  it 
does so with pretty much 0 runtime overhead.
-mike
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part.
Url : http://lists.denx.de/pipermail/u-boot/attachments/20101022/ef1945ae/attachment.pgp 


More information about the U-Boot mailing list