malloc: errno: 22: Invalid argument

John Levine johnl at iecc.com
Sat Apr 9 15:10:41 UTC 2011


>-- snip
>#include <err.h>
>#include <errno.h>
>#include <stdlib.h>
>
>int main(void)
>{
>        int *i;
>        warn("errno: %d", errno);
>        i = malloc(sizeof(int));
>        warn("errno: %d", errno);
>        free(i);
>        return (errno);
>}
>-- snip

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.

Regards,
John Levine, johnl at iecc.com, Primary Perpetrator of "The Internet for Dummies",
Please consider the environment before reading this e-mail. http://jl.ly


More information about the freebsd-questions mailing list