Re: pass a local variable to a function

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



明亮 wrote:

> 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.

It's perfectly acceptable to pass a local variable to or from a
function. It's also acceptable to pass the address of a local variable
to a function.

What isn't acceptable is returning the address of a local variable
from a function, as the variable will cease to exist once the function
returns.

> 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;

This returns the address of the local variable "string", which isn't
valid.

>     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?

Making the array larger means that the start address is further down
the stack (most common architectures use a descending stack). The
printf() call is presumably using less than 1K of stack, so it doesn't
overwrite the variable.

This won't work if the platform uses an ascending stack, or if it
returns unused stack memory to the OS, or if printf() uses more than
1K for local variables (directly or indirectly), or if the
architecture handles signals, interrupts, etc using the same stack as
the main thread. There are other possible reasons why it may fail.

If you want to understand the internals of program execution, learn
assembly language and examine the disassembled code.

-- 
Glynn Clements <glynn@xxxxxxxxxxxxxxxxxx>
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux