Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 10 Apr 2011 10:47:10 +0200
From:      Polytropon <freebsd@edvax.de>
To:        freebsd-questions@freebsd.org
Subject:   Re: malloc: errno: 22: Invalid argument
Message-ID:  <20110410104710.f8c14744.freebsd@edvax.de>
In-Reply-To: <BANLkTikpcMQmw8YrmC-yCH2xqW5%2B2EqR3Q@mail.gmail.com>
References:  <BANLkTikEZHkQhLYz9-gEGfJnSoDWSAKFxA@mail.gmail.com> <20110409144336.72626.qmail@joyce.lan> <BANLkTikpcMQmw8YrmC-yCH2xqW5%2B2EqR3Q@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sat, 9 Apr 2011 17:17:06 +0200, Sami Kerola <kerolasa@iki.fi> wrote:
> On Sat, Apr 9, 2011 at 16:43, John Levine <johnl@iecc.com> wrote:
> > Your code is wrong. =A0There's only a useful value in errno after
> > something fails. =A0This would be more reasonable:
> >
> > int main(void)
> > {
> > =A0 =A0 =A0 =A0int *i;
> > =A0 =A0 =A0 =A0/* warn("errno: %d", errno); -- no error, nothing to che=
ck */
> > =A0 =A0 =A0 =A0i =3D malloc(sizeof(int));
> > =A0 =A0 =A0 =A0if(!i)warn("errno: %d", errno); /* only warn on failure =
*/
> > =A0 =A0 =A0 =A0free(i); =A0 =A0/* -- free ignores NULL argument */
> > =A0 =A0 =A0 =A0return (0); /* -- free cannot fail, no meaningful errno =
*/
> > }
> >
> > This isn't specific to FreeBSD, by the way. =A0It's ANSI C.
>=20
> Different systems seem to work different ways. Indeed you are right,
> the behavior of operating system setting errno when malloc is
> successful is allowed.
>=20
> http://pubs.opengroup.org/onlinepubs/009695399/functions/errno.html
> http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html
>=20
> 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.




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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20110410104710.f8c14744.freebsd>