malloc: errno: 22: Invalid argument

Polytropon freebsd at edvax.de
Sun Apr 10 08:47:13 UTC 2011


On Sat, 9 Apr 2011 17:17:06 +0200, Sami Kerola <kerolasa at iki.fi> wrote:
> On Sat, Apr 9, 2011 at 16:43, John Levine <johnl at iecc.com> wrote:
> > Your code is wrong.  There's only a useful value in errno after
> > something fails.  This would be more reasonable:
> >
> > int main(void)
> > {
> >        int *i;
> >        /* warn("errno: %d", errno); -- no error, nothing to check */
> >        i = malloc(sizeof(int));
> >        if(!i)warn("errno: %d", errno); /* only warn on failure */
> >        free(i);    /* -- free ignores NULL argument */
> >        return (0); /* -- free cannot fail, no meaningful errno */
> > }
> >
> > This isn't specific to FreeBSD, by the way.  It's ANSI C.
> 
> Different systems seem to work different ways. Indeed you are right,
> the behavior of operating system setting errno when malloc is
> successful is allowed.
> 
> http://pubs.opengroup.org/onlinepubs/009695399/functions/errno.html
> http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html
> 
> Perhaps it was just a naive beginner expectation that errno is not set
> by functions when they are successful. I'll remove the check from the
> end of the program since there is no guarantees it would mean anything
> sensible.

Allow me an addition:

For meaningful main() return values, use EXIT_SUCCESS or
EXIT_FAILURE (as defined in stdlib.h) instead of the errno
set by a function. This is the always portable "test for
zero", as in "everything okay -> zero; error -> not zero,
usually 1, but primarily NOT ZERO". :-)

FreeBSD allows more detailed return values like EX_CONFIG,
EX_USGE or EX_SOFTWARE (as defined in sysexits.h), but I'm
not sure if this is fully portable across all BSDs, UNIX,
and the various Linusi.




-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list