
Returning pointers from functions ...
Quote:
(Chris Trueman) writes:
>... However, I am unsure about using the:
>return(buf)
>as this implies to me that a pointer to a locally defined buffer - buf
>is actually being returned.
C includes two major sub-parts, `values' and `objects'. An object is
something that holds a value, and a value is one of the obvious
things---such as a number like 3.14 or 42---or one of C's more {*filter*}
varieties, such as pointers.
Quote:
>As it has been defined locally at the end of the function the space
>is made available for later use.
The word `it' here dangles---do you mean the buffer, or the variable
`buf'? Perhaps they are the same, perhaps not; the original article
does not include enough context to say.
One of C's oddities is that an array object `acts up' when you try to
take its value. Thus, if you have:
char buf[100];
then `buf' is an array object containing 100 sub-objects, but the
`value' of `buf' is a pointer to the first sub-object, rather than the
100 values of the 100 sub-objects. This is due to The Rule (detailed
in other articles). You must memorize The Rule in order to deal with
arrays and pointers correctly, just as you must memorize the rules of
arithmetic in order to add and subtract. The rules are in some sense
arbitrary, but they make the system work.
On the other hand, perhaps you have:
char *buf;
In this case buf is not an array object, and its value is straightforward.
In either case, objects in C have lifetimes or *durations*. For
ordinary variables, there are only two; these are known as `static' and
`automatic'. Static objects last for the entire program run, while
automatic objects exist only during the execution of their enclosing
block. Once the block exits, the objects it defined are no longer
valid. (Whether they still exist anywhere is machine-dependent. On
most machines, they do, and you can get in trouble because it is hard
to predict when their memory is reused, so your programs appear to work
`randomly'.)
There is an additional storage duration that has no official name; it
is often called `heap space' or `managed memory'. Space allocated via
malloc() and its friends is good until free()d, or until the program
exits. This space also consists of objects and can therefore hold
values.
Given the declaration:
char *buf;
then if buf points to heap space or to a static object,
return (buf);
returns a valid value. On the other hand, given:
char buf[100];
then if buf has static duration,
return (buf);
returns a valid value (namely &buf[0]), but if buf has automatic
duration, it returns an invalid value (because &buf[0] no longer
exists, at least in principle, by the time the `return' completes).
Similarly, given:
char xbuf[100];
...
char *buf = &xbuf[0];
then:
return (buf);
is valid if and only if xbuf still exists after the return (i.e.,
xbuf has static duration or is declared in a still-active block).
--
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 510 486 5427)