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

Reinhard Meyer
2010-10-22T07:18:02Z

Dear Joakim Tjernlund,
> Mike Frysinger <vapier@gentoo.org> wrote on 2010/10/21 21:51:53:
>> On Thursday, October 21, 2010 07:45:10 Joakim Tjernlund wrote:
>>> Wolfgang Denk wrote on 2010/10/21 13:32:54:
>>>> Joakim Tjernlund you wrote:
>>>>>> - if ((long)bytes < 0) return 0;
>>>>>> + if ((long)bytes <= 0) return 0;
>>>>> I think you should return some impossible ptr value =! NULL
>>>>> Size 0 not really an error.
>>>> It is legal for malloc() to return NULL in case of size==0,
>>>> and for the sake of simplicity I recommend we do just that.
>>> Yes, but not very useful. Glibc does not return NULL
>> 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.

My five cents:

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

Your example is in the right way, but a bit flawed in its simplicity.
Even empty lines need some form of information that they are of length zero,
be it a 0x00 in the memory line itself (requiring malloc(length+1)) or that same
information in a variable somewhere else:
struct line {
byte *buf;
int length;
} lines[...];

As an (undercover) Mathematician:
Out of principle I would say that malloc(0) should return a non-NULL
pointer of an area where exactly 0 bytes may be used. And, of course,
free() of that area shall not fail or crash the system.

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

>> why exactly do you want malloc(0) to return valid memory ? i would
> rather
>> have u-boot return an error.

In the case of u-boot, where a driver or whatever should never really need
to allocate zero memory, such a programming error should be made obvious by
at least a warning message.

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

Makes sense only if any access outside of any allocated memory would behave
the same, otherwise this is a special case again.

Best Regards,
Reinhard