Re: Returning automatic pointers always bad?
- From: Richard <rgrdev_@xxxxxxxxx>
- Date: Sat, 28 Feb 2009 05:16:41 +0100
pete <pfiland@xxxxxxxxxxxxxx> writes:
C. J. Clegg wrote:
Consider the following:
char *foo( void )
{
char *bar = (char *)NULL;
bar = malloc( 40 );
return bar;
}
int main( void )
{
char *foobar = (char *)NULL;
foobar = foo();
doSomethingWith( foobar );
free( foobar ); // safe even if foobar is NULL
foobar = (char *)NULL;
return 0;
}
Now, foo( ) is returning an automatic pointer, which as we all know
goes out of scope as soon as foo( ) returns. In this case, that
should be OK, right?... because that pointer is assigned to another
pointer (foobar in main()) which continues to point to valid heap
memory even if bar goes out of scope.
The code is OK but your reasoning is wrong.
foo returns the same value returned by malloc.
It makes no difference whether or not an automatic variable
once held this value before foo returns.
His reasoning was correct enough if you dig into what he said : "the
pointer is assigned to another pointer which then continues to point to
valid memory". Implicit is "pointer value" when mentioning assigning a
"pointer" in this kind of chat.
.
If foobar were indeterminate, then there would be a problem with
doSomethingWith( foobar );
char *foo2(void){return malloc(40);}
There's no difference between what your foo does and what foo2 does.
There's no difference between the way that your foo can be used
and the way that foo2 can be used.
- Follow-Ups:
- Re: Returning automatic pointers always bad?
- From: pete
- Re: Returning automatic pointers always bad?
- References:
- Returning automatic pointers always bad?
- From: C . J . Clegg
- Re: Returning automatic pointers always bad?
- From: pete
- Returning automatic pointers always bad?
- Prev by Date: Re: Returning automatic pointers always bad?
- Next by Date: Re: Returning automatic pointers always bad?
- Previous by thread: Re: Returning automatic pointers always bad?
- Next by thread: Re: Returning automatic pointers always bad?
- Index(es):
Relevant Pages
|