malloc: errno: 22: Invalid argument

Sami Kerola kerolasa at
Sat Apr 9 15:17:08 UTC 2011

On Sat, Apr 9, 2011 at 16:43, John Levine <johnl at> 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.

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

   Sami Kerola

More information about the freebsd-questions mailing list