[comp.lang.c] returning automatic variables

nnj20229@uxa.cso.uiuc.edu (Nesha Nicole Jones) (05/24/91)

I wrote the following simple program and when it runs I get the following 
output.  Is it possible to return an automatic string form a function
because I cannot get it to work.

#include <stdio.h>

main()
{
        char machine[100];
        char *word(void);

        sprintf(machine,"%s",word());
        printf(" the value of name after the function call is %s\n",machine);

}

char *word(void)
{
        char name[100];

        printf("enter a value for name : ");
        scanf("%s",name);
        return name;
}
******************* output ***********************************

enter a value for name : nesha
 the value of name after the function all is oo$


** I copied this directly from the screen , you could not see the ^?^?o^?o^?$

henry@zoo.toronto.edu (Henry Spencer) (05/24/91)

In article <1991May24.153133.13590@ux1.cso.uiuc.edu> nnj20229@uxa.cso.uiuc.edu (Nesha Nicole Jones) writes:
>... Is it possible to return an automatic string form a function...

Basically, no.  The string has to be contained in storage that will survive
after the function returns.  Automatic variables don't.  You either have to
use a static buffer for the returned value, or use malloc().
-- 
And the bean-counter replied,           | Henry Spencer @ U of Toronto Zoology
"beans are more important".             |  henry@zoo.toronto.edu  utzoo!henry

gwyn@smoke.brl.mil (Doug Gwyn) (05/25/91)

In article <1991May24.153133.13590@ux1.cso.uiuc.edu> nnj20229@uxa.cso.uiuc.edu (Nesha Nicole Jones) writes:
>char *word(void)
>{
>        char name[100];
...
>        return name;
>}

You're not returning the value of an auto variable, but rather a pointer
to it.  However, the auto variable "goes out of scope" (becomes invalid)
upon return from the function; therefore what is pointed at by the
returned pointer is no longer valid.

There are several possible solutions, the simplest being to declare the
name[] array as having static storage duration.

phil@ux1.cso.uiuc.edu (Phil Howard KA9WGN) (05/25/91)

nnj20229@uxa.cso.uiuc.edu (Nesha Nicole Jones) writes:

>I wrote the following simple program and when it runs I get the following 
>output.  Is it possible to return an automatic string form a function
>because I cannot get it to work.

No.  Either allocate a string (and be sure to free it) or use static.
In the case of static, the contents of the string will change the next
time your function is used.

BTW, what if I type in more than 99 characters into your string?
-- 
 /***************************************************************************\
/ Phil Howard -- KA9WGN -- phil@ux1.cso.uiuc.edu   |  Guns don't aim guns at  \
\ Lietuva laisva -- Brivu Latviju -- Eesti vabaks  |  people; CRIMINALS do!!  /
 \***************************************************************************/