Re: using local buffers.

From: Edward Almasy (almasy@axis.com)
Date: 09/14/95


Ron Poulton writes:
> Btw, I know I can 'return "string"' in order to return a string from a 
> char* function, but if I have a local buffer, how would I return a string 
> in the same manner without returning the address of the local buffer?

Two ways:  1) Allocate a string (via CREATE() or malloc()) and copy the
characters from the local buffer to the allocated string using strcpy()
or strncpy(), or  2) declare the local buffer "static" so that it persists
and return a pointer to it.

Method #1 is definitely preferable, although it means that the caller
has to deallocate the string when they're done with it.  You can also
combine the allocation and copy by using strdup() (or str_dup() in Circle).


[Rant Mode ON]

Regarding local buffers in general:  I would say this whole discussion
is a very good illustration of why global variables are usually a terrible
idea and should be avoided at almost any cost.

Section 10.6 of the book Code Complete by Steve McConnell (Microsoft
Press, 1993, ISBN 1-55615-484-4) has a very good discussion of the issues
surrounding global versus local variables.  If you write software for
a living (or would like to), this is a book that you should own.  I can't
recommend it highly enough - if I could have bought this book ten years
ago I would have gladly paid $1,000 for it.

(I'm not exaggerating about the $1,000.  Code Complete contains so much
wisdom that it would have paid for itself in terms of headaches avoided
inside of six months.  The actual cover price on the book ($35) is trivial
compared to the value within.)

[Rant Mode OFF]


 \_\_\_     _/ \_\_\_  axis data: specializing in online system setup & design
 \_  \_     _/ \_  \_    Edward Almasy                       almasy@axis.com  
 \_\_\_     _/ \_\_\_    President: Axis Data   Proprietor: NineJackNine BBS
     \_ _/  _/     \_    608-256-5732 (voice)            608-256-5697 (data)
 \_\_\_ _/_/_/ \_\_\_  9jack9: on the bleeding edges of culture and technology



This archive was generated by hypermail 2b30 : 12/07/00 PST