Re: pass a local variable to a function

Lorenzo Beretta <[email protected]>
Newsgroups org.kernel.vger.linux-c-programming
Message-ID <[email protected]>
明亮 ha scritto:
> 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 [email protected]
> More majordomo info at  http://vger.kernel.org/majordomo-info.html
> 

Try something like this
------
void p(int n){
	int onstack;
	printf("%p\n", &onstack);
	if(n>0) p(n-1);
}

int main(){
	p(5);
	return 0;
}
------

It should (system dependant) print a sequence of decreasing hex numbers;
that's because each time you call a function on your computer, the local 
stack grows downwards.

When you scanf() into a character array, it writes into the first 
characters of your array, that is string[0], then string[1], and so on: 
notice that the address of string[1] is GREATER than the address of 
string[0]...

Summing up there are two cases (assume that X stands for "any value"):

1) string[10]
==> { X, X, X, X, X, X, X, X, '\0', 'a' }
2) string[1024]
==> { X, X, X, (long sequence of garbage)..., '\0', a' }

When you call printf(), the printf function overwrites some bytes for 
its own stack variables: if it takes more than 10 bytes (eg 42), the 
small array will be completely overwritten, while with the big array it 
will only overwrite string[1023...980] (which was garbage anyway!), 
leaving string[0...979] intact.

I hope that was helpful; try gooling "buffer overflow" for more info


lb

--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.