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

Graeme Russ
2012-04-02T03:05:51Z

Hi Marek,

On Mon, Apr 2, 2012 at 12:51 PM, Marek Vasut <marek.vasut@gmail.com> wrote:
> Dear Graeme Russ,
>
>> Hi Marek,

>> Bottom line is, we could do either and we would be 100% compliant with the
>> C standard
>>
>> The question is, what would be more onerous. Since the majority of U-Boot
>> developers will be more familiar with the glibc implementation, we may
>> one day end up with code that blindly assumes malloc(0) returns a valid
>> pointer and not NULL so to me, returning a valid pointer would be a logical
>> choice.
>>
>> On the converse, returning NULL from malloc(0) means that any attempt to
>> (illegally) deference it will be immediately obvious...
>
> So it's a question of being fool-proof vs. being compatible with glibc. This is
> a tough one, so what about voting ? ;-)
>

#define CONFIG_SYS_GLIBC_MALLOC_COMPAT

Kidding

Consider:

void some_function_a(void)
{
uchar *blah;
blah = malloc(1);

if(blah)
blah[1] = 'x';
else
printf("E_NOMEM\n");
}

void some_function_b(void)
{
uchar *blah;
blah = malloc(0);

if(blah)
blah[0] = 'x';
else
printf("E_NOMEM\n");
}

Both will corrupt data if malloc(0) returns a valid pointer. But:

void some_function_b(int i)
{
uchar *blah;
blah = malloc(i);

if(blah)
blah[i] = 'x';
else
printf("E_NOMEM\n");
}

Will return E_NOMEM if i == 0 and corrupt data is i > 0

It's inconsistent.

I originally thought returning NULL was the most appropriate option, but
seeing the FDT example and thinking how malloc(0) returning a valid pointer
has the potential to simplify (and hence make smaller and faster) code in
some circumstances.

My vote is for glibc compatibility

Regards,

Graeme