(char *)(-1)
Chris Torek
chris at mimsy.UUCP
Fri Jul 28 20:29:03 AEST 1989
>>... if NULL is returned there was an error getting the next string,
>>if (-1) is returned there were no more symbols.
In article <1063 at tukki.jyu.fi> tarvaine at 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 at 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 at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.std.c
mailing list