On Tue Nov 22, 2005 at 13:51:59 +0800, [EMAIL PROTECTED] wrote:
>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;
>}
>
>somefunction returns string2 which is trash!
>formally: The scope of string2 does not extend to main!
>(even if it works, and it might, it's WRONG)

"some words" will be allocated in the .rodata section not on the stack
so it will actually work. (Not that I'd recommend doing this!!).

I can't find anything in the C spec about return the address of a string 
literal,
it doesn't say wether it is allowed or not.

If course if the code was:

char *
somefunction()
{
        char string2[] = "some words";
        return string2;
}


That would definately be wrong (and would sometimes work ;). Gcc warns about
this, but not the above in gcc -Wall. (Not that that means anything..)


To see exactly how it dies try this:

int
main(void)
{
        char *s = foo();
        char *d;
        d = alloca(37);
        /* Allocate stuff on the stack -- will trash somefunction return */
        strcpy(d, "foo bar baz blerg ");
        printf("s: %s\n", s);
        return 0;
}


Whereas as with the orginal somefunction this would work.


>> Moral of the story is don't code in C ;);) Or if you do use as many tools
>> to help you as possible. -Wall, and a C linter are a good start.
>> Valgrind is also meant to be good, although I haven't
>> used it.
>
>If you're going to drive a sports car, learn to use the clutch!
>He's learning. For sleek and mean there is no better (than C), but it does 
>require care and diciplin

Well there is assembler ;) But there is definately times when using C is a
good idea, it is just easy to fuck up.

Benno
-- 
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to