linux-c-programming.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* pass a local variable to a function
@ 2009-03-25 16:21 明亮
  2009-03-25 17:17 ` Lorenzo Beretta
                   ` (3 more replies)
  0 siblings, 4 replies; 6+ messages in thread
From: 明亮 @ 2009-03-25 16:21 UTC (permalink / raw)
  To: linux-c-programming

Hi guys,

This is my first email in this list, any help is much appreciated.
As I know, it's not allowed to pass a local variable to a function,
because the stack where local variable resides will be reused by other
functions.
eg:
     1  #include <stdio.h>
     2
     3  char *fetch();
     4
     5  int main(int argc, char *argv[]){
     6          char *string;
     7          string = fetch();
     8          printf("%s\n", string);
     9          exit(0);
    10  }
    11
    12  char *fetch(){
    13          char string[10];
    14          scanf("%s", string);
    15          return string;
    16  }

When the application is executed, after input "a", it will produce
unknown characters, like "8Šè¿ôÿO". Which is like what I expect

However, if I change line 13 to:
    13           char string[1024];

When I type "a", it echos "a", which is out of my expectation

Why does it behave like this?

Thanks in advance,
longapple
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@vger.kernel.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2009-03-26 13:09 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2009-03-25 16:21 pass a local variable to a function 明亮
2009-03-25 17:17 ` Lorenzo Beretta
2009-03-26 13:09   ` Mingliang
2009-03-25 18:50 ` Bert Wesarg
2009-03-26  8:42 ` Glynn Clements
2009-03-26  9:49 ` Jon Mayo

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).