[U-Boot] [PATCH] Prevent malloc with size 0
Joakim Tjernlund
joakim.tjernlund at transmode.se
Mon Apr 2 08:39:29 CEST 2012
Graeme Russ <graeme.russ at gmail.com> wrote on 2012/04/02 05:05:51:
>
> Hi Marek,
>
> On Mon, Apr 2, 2012 at 12:51 PM, Marek Vasut <marek.vasut at 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.
:) exactly how I started too. I always figure malloc(0) should return NULL until
a few years ago when I tripped on a use case where it was inconvenient and it got me thinking.
It is like the early math systems were one didn't have 0 at all. You got away with it
for a long time but in the end one really need 0.
Jocke
More information about the U-Boot
mailing list