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

Joakim Tjernlund joakim.tjernlund at transmode.se
Fri Oct 22 09:37:43 CEST 2010


Mike Frysinger <vapier at gentoo.org> wrote on 2010/10/22 09:20:22:
> 
> 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)

Yes, the example was a little flawed but the was the best I could come
up with on short notice. I am sure my point was understood anyway.

> 
> > 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"

Yes, and that and that is even worse. How do you tell if you are out of 
memory
or not? Checking size == 0 after the fact? Then you could do that
before calling malloc in the first place.
 
> concept.  but i dont see how this matters as i dont see any example in 
u-boot 
> context where malloc(0) is a problem.

This is bigger than u-boot and you just because there isn't someone using 
it
today(how can you when it corrupts memory), that might change in the 
future.

> 
> > > 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.

hardly as glibc returns a non NULL ptr. Changing this would probably
break apps, making them think they are out of memory.

non null still what it is supposed to mean, you successfully allocated
0 bytes.

> 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.

You lost me here. How does this relate to the issue before us?



More information about the U-Boot mailing list