[vox-tech] C: functions that return a string

Jeff Newmiller vox-tech@lists.lugod.org
Wed, 30 Jan 2002 15:41:01 -0800 (PST)


On Wed, 30 Jan 2002, Peter Jay Salzman wrote:

> i have a function, GetCPUType(), that returns a local (but static)
> string.  this works from main():
> 
>    char buf[BUFFERSZ];
>    strcpy(buf, GetCPUType(proc_cpu));
>    printf("CPU Type: %s", buf);
> 
> this doesn't (it prints garbage):
> 
>    printf("CPU Type: %s", GetCPUType(proc_cpu));
> 
> the function looks like:
> 
>    char *GetCPUType(const char *file)
>    {
>       static char *ptr;
>       /* do stuff with ptr */
>       return ptr;
>    }
> 
> what's the difference between putting ptr into a buffer and printing the
> buffer vs. printfing the pointer to a string directly?  ptr ends with
> \0.

A char pointer is a pointer... it occupies four bytes, and must be
initialized to point at something.  It does not end in '\0' (that is like
saying one of the squares in a quilt is a sphere), but the memory it
points to may.

A char array has a name, and that name can "decay" into a pointer to the
beginning of that array.

How about something like:

    char *GetCPUType( const char *file )
    {
       static char buf[ BUFFERSZ ];
       /* fill up buf */
       return buf;
    }

but beware of:

    char *GetCPUType( const char *file )
    {
       char buf[ BUFFERSZ ]; /* on stack */
       /* fill up buf */
       return buf;
       /* memory allocated on stack for buf disappears,
          leaving dangling pointer */
    }

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil@dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...2k
---------------------------------------------------------------------------