Article View: comp.std.c
Article #385Re: (char *)(-1)
From: Chris Torek
Date: Fri, 28 Jul 1989 10:29
Date: Fri, 28 Jul 1989 10:29
56 lines
2212 bytes
2212 bytes
>>... if NULL is returned there was an error getting the next string,
>>if (-1) is returned there were no more symbols.
In article <1063@tukki.jyu.fi> tarvaine@tukki.jyu.fi (Tapani Tarvainen) writes:
>Is it safe to return -1?
No. (Incidentally, that is not the only problem with the code in
<118@psitech.UUCP>.)
>I mean, isn't it possible that (char *)(-1) is a valid pointer
>in some system and could have been returned by malloc() ... ?
This is entirely possible (although it will be false on most Unix
systems, for SysV and BSD and V7 backwards-compatibility reasons;
this will probably be true for at least another ten years).
It is also possible that (char *)(-1) is a run-time exception, or
even a compile-time exception.
>If -1 isn't safe, is there any other value (besides NULL) that can
>safely be returned from a (any *) function to indicate error?
There is no single value. One common approach is to return either
the address a dynamically allocated object, NULL, or the address of
one of several statically objects. For instance:
#include <stddef.h> /* defines malloc, etc */
#include "widget.h" /* defines widget things */
struct widget error_widget;
struct widget *
make_a_widget(sometype somearg) {
struct widget *p;
/* check arguments */
if (BADARG(somearg))
return &error_widget;
/* make a new widget */
p = malloc(sizeof *p);
if (p == NULL)
return NULL;
/* set it up */
.
.
.
return p;
}
Another approach is to return NULL for all exceptions, and provide
an additional status variable or function.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris
Technical Details
Message-ID:
<18792@mimsy.UUCP>Path:
arc1-ca.pugleaf.net!utzoo!attcan!utgpu!watmath!iuvax!uxc.cso.uiuc.edu!tank!mimsy!chrisReferences:
<GEOFF.89Jun11231924@onyx.cs.warwick.ac.uk> <2619@yunexus.UUCP> <118@psitech.UUCP> <1063@tukki.jyu.fi>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!attcan!utgpu!watmath!iuvax!uxc.cso.uiuc.edu!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.std.c Subject: Re: (char *)(-1) Keywords: pointers, casts Message-ID: <18792@mimsy.UUCP> Date: 28 Jul 89 10:29:03 GMT References: <GEOFF.89Jun11231924@onyx.cs.warwick.ac.uk> <2619@yunexus.UUCP> <118@psitech.UUCP> <1063@tukki.jyu.fi> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 56