On 11/22/05, Crossfire <[EMAIL PROTECTED]> wrote:
[snip]
> >>>Ummmm ...
> >>>
> >>>Coding 3.
> >>>#include <stdio.h>
> >>>#include <stdlib.h>
> >>>#include <string.h>
> >>>char *
> >>>somefunction()
> >>>{
> >>> char *string2 = "some words";
> >>> return string2;
> >>>}
> >>>int main (void)
> >>>{
> >>> char *string;
> >>> string = somefunction();
> >>> printf ("\n\nString is: %s\n\n", string);
> >>> return 0;
> >>>}
> >>>
O Plameras was once rumoured to have said:
> After somefunction() returns, it has the address of the first character
> in "some words".
> I assign that address to string. I print the contents of that address up
> to character '\0'.
> This is done by printf.
>
> This is a fundamental concept you're missing.
No, you're missing it. Here's a slightly nastier example[1] which
demonstrates why what you're doing is wrong and should not be done.
---BEGIN---
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *
somefunction()
{
auto char string2[] = "some words";
return string2;
}
void
anotherfunction()
{
auto int i,r[50];
/* build a 'random' sequence on the stack to prove the point. */
for (i = 0; i < 50; i++) {
r[i] = (i*13)%256;
}
}
int main (void)
{
char *string;
string = somefunction();
anotherfunction();
printf ("\n\nString is: %s\n\n", string);
return 0;
}
---END---
string still contains a pointer to the start of the string "some
words", right?
Now, before chickening out and running it, predict the outcome.
This is why you don't return pointers from stuff defined in local
subroutine scope.
C.
[1] I expect Benno and Erik to immediately spot the subtle difference. ;)
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html
Wow, I remember when this thread had just 3 messages.
Anyway, just trying to clarify from the above code: "string2" is a pointer to an automatic variable - a character array? Very bad to pass this address back to main().
But if you had said
char * string2 = "some words"
or even
auto char * string2 = "some words"
it will work (at least as I've just tested with gcc) because you've initialised a pointer to a string literal, which pretty much is set in stone for the life of the program. (Nor can you alter its contents)
So:
1) char string2[] = "string literal";
- string2 is created with separate location (an address on the stack in the above code) to "string literal" and "string literal" is copied into it.
2) char *string2 = "string literal";
- string2 holds an address of "string literal" which is not on the stack
Daniel.
-- SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/ Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html
