On Tue Nov 22, 2005 at 17:51:38 +1100, O Plameras wrote:
>[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!
>> 
>>
>
>string2 is the return value of
>
>char * somefunction which is extern ( or GLOBAL).

Sure, but the scope of string2 is local to somefunction. The
thing is string2 is only a pointer, it isn't the actual memory.

The function could have also been written with perhaps less confusion
as:

char *somefunction() {
        return "some words";
}

The reason I don't like this style is that presumably somefunction() will
in the future actually *do something* to generate a string. And then simply
returning something like this no longer works -- you need to allocate something
on the heap. And then it changes the interface you have with the client, because
currently they are not allowed to free() what is returned. (And on any decent OS
should actually crash, because writing to rodata shouldn't be allowe). However
once you alloc then the interface becomes subtly differnt because the
client must free() or else leave a memory leak. Which is bad for any long 
running
process.

And of course if somefunction() has to return some error code, not just the
string you also need to get more trickier with pointers, and end up with
what I had before.

*but*, having any interface where you allocate data inside a function and
expect to free is elsewhere is genreally bad, because it is too
easy to screw up, and forget the free, probably better to supply a buffer
if possible (with a length of course). Of course that means having some 
expection
of the size required in the first place.

(Can people start to see why I say doing C right is difficult??)

If somefunction is really constant you might as well refactor as:

const char somewords[] = "some words";

and avoid the confusion.

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