problem about pointer used as function return type 
Author Message
 problem about pointer used as function return type

Hello,
Pls help , I am always puzzled by the following problem.
Say I design a function "char *called(void)" to return a pointer to
characters
as follows:

char *called(void)
{
   char sentence[1024];

    ......

   return sentence;

Quote:
}
>From the perspevtive of the calling function, say "void calling()" as

folows:

void calling()
{
   char *line;

   line=called();

Quote:
}

inside the calling function, I may use a pointer to characters to be
assigned the returning pointer from the called function. Now, this
means a pointer in the calling function holding an address of a local
area(variable), i.e, "sentence", in the called function. Is this
allowed or will cause trouble? I thought the local varible "sentence"
in the called function will be perish once the execution sequence is
out of  that called function, which implies the character pointer
varible I used in the calling function, i.e., "line", pointing to a
perished local area.

If I call the "called" function 10 time and use an array of pointers
to hold
all the returned addresses from the function "called", am I pointing
to 10
different local copyies of the perishing local variable "sentence"?

Pls explain this to me. Thank you in advance for your help.

Dan
--



Thu, 17 Mar 2005 12:56:21 GMT  
 problem about pointer used as function return type

Quote:
> Hello,
> Pls help , I am always puzzled by the following problem.
> Say I design a function "char *called(void)" to return a pointer to
> characters
> as follows:

> char *called(void)
> {
>    char sentence[1024];
>    ...
>    return sentence;
> }

This function returns garbage.

Quote:
> inside the calling function, I may use a pointer to characters to be
> assigned the returning pointer from the called function.

not a good idea with the preceding function.

Quote:
> means a pointer in the calling function holding an address of a local
> area(variable), i.e, "sentence", in the called function. Is this
> allowed or will cause trouble? I thought the local varible "sentence"
> in the called function will be perish once the execution sequence is
> out of  that called function, which implies the character pointer
> varible I used in the calling function, i.e., "line", pointing to a
> perished local area.

Correct.

Quote:

> If I call the "called" function 10 time and use an array of pointers
> to hold all the returned addresses from the function "called", am I
> pointing to 10 different local copyies of the perishing local variable
> "sentence"?

You are holding pointers to garbage.

You can do:

char *called(void)
{
        static char sentence[1024];
        return sentence;

Quote:
}

which will return the address of the static array sentence (does not
change) with each call.

on the other hand, you could also do:

char *called(void)
{
        return malloc(1024);

Quote:
}

which will return freshly allocated memory. the caller will then be
responsible for free'ing this area.

Sinan.
--
A. Sinan Unur

Remove dashes for address

--



Sat, 19 Mar 2005 21:56:03 GMT  
 problem about pointer used as function return type

Quote:

> I thought the local varible "sentence"
> in the called function will be perish once the execution sequence is
> out of  that called function, which implies the character pointer
> varible I used in the calling function, i.e., "line", pointing to a
> perished local area.

That's right.

Quote:
> If I call the "called" function 10 time and use an array of pointers
> to hold
> all the returned addresses from the function "called", am I pointing
> to 10
> different local copyies of the perishing local variable "sentence"?

That depends on the implementation, and the language standard does
not guarantee that you can make use of what might be pointed to by
any of those pointer values.  *Most* implementations will allocate
the local variable in a run-time stack location that will be the
same for each invocation of the function from the same context, but
it is not generally safe to assume that therefore the last-stored
value of the local variable is still stored there, as the stack
space may be reused by the calling function after the return from
the called function.
--



Sat, 19 Mar 2005 21:56:47 GMT  
 problem about pointer used as function return type
Quote:

> Hello,
> Pls help , I am always puzzled by the following problem.
> Say I design a function "char *called(void)" to return a pointer to
> characters
> as follows:

> char *called(void)
> {
>    char sentence[1024];

>     ......

>    return sentence;
> }

[...]

The problem is that you are returning a point to an array that no longer
exists after returning.  Therefore, the pointer is invalid.

You could use something like this:

    char *called(void)
        {
        static char sentence[1024];
        ...
        return sentence;
        }

Of course, this would re-use the same buffer every time, so you would
have to take this into account.

Another method would be to allocate the buffer each time:

    char *sentence = malloc(1024);
    if ( sentence == NULL )
        return NULL;
    ...
    return sentence;

This, of course, would require that the calling routine free() the
buffer when done, unless you like memory leaks.  (As well as check
for NULL returns.)

There are other methods as well.  Which one you choose depends on
the particular situation at hand.  The main thing to remember is that
you cannot return a pointer to something that will no longer exist
once you return.

--

+---------+----------------------------------+-----------------------------+
| Kenneth |     kenbrody at spamcop.net      | "The opinions expressed     |
|    J.   |    http://www.hvcomputer.com     |  herein are not necessarily |
|  Brody  |      http://www.fptech.com       |  those of fP Technologies." |
+---------+----------------------------------+-----------------------------+
--



Sat, 19 Mar 2005 21:58:34 GMT  
 problem about pointer used as function return type

Quote:

> char *called(void)
> {
>    char sentence[1024];
>    return sentence;
> }

Storage for sentence[1024] is allocated in the stack frame for the
function called(). When called() returns, the pointer you return still
points there.

Quote:
> void calling()
> {
>    char *line;
>    line=called();
> }

The pointer you assign to line points to a now non-existent stack
frame.

You probably want to allocate array sentence on the heap (using
malloc() and friends) and return the pointer malloc() returns.

--
Intra-mural sports results are filtering through th' plumbing...
--



Sat, 19 Mar 2005 22:01:41 GMT  
 problem about pointer used as function return type

writes

Quote:
>char *called(void)
>{
>   char sentence[1024];

>    ......

>   return sentence;
>}

The returned pointer is often called a{*filter*} pointer (probably because
that is what you should do with a programmer who writes such code:-) It
has undefined behaviour. Unfortunately from the perspective of learning
NOT to write such code it will appear to work for simple test cases
because on most systems the stack has not yet been overwritten.
Consider:

void overwrite(){
  char* s = called();
  puts(s);      // all seems to be fine
  s = called();
  puts(s);           // you get the new version
  somethingelse();
  puts(s);           // who knows, maybe you just reformatted your
harddrive

Quote:
}

That last outcome would be extraordinarily bad luck but many lesser
deeply dangerous results can happen.

For example consider a variant of the above:

void wipestack(){
   char array[1024];
   char * s = called();
// call some other functions
   strcpy(array, s);

Quote:
}

And there is a pretty good chance that you overwrite a return address on
the call stack and now all bets are off.

--
Francis Glassborow      ACCU
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation
--



Sat, 19 Mar 2005 22:01:44 GMT  
 problem about pointer used as function return type
[...]

Quote:
> Is this allowed or will cause trouble?

Will cause trouble.  All kinds of.  Don't do that.

For that technique to become allowed, you have to mark the local
variable of the called function "static".  This extends its lifetime
to that of the whole program.  But it also means there's only a single
instance of this variable, during the whole lifetime of the program.
I.e. if you call the function several times, all returned points will
point to the *same* object.  The changes made to it by one call will
immediately affect all earlier results (and render your program
threading-unsafe while being at it).

See the FAQ for recommendations of alternate practices.
--

Even if all the snow were burnt, ashes would remain.
--



Sat, 19 Mar 2005 22:01:46 GMT  
 problem about pointer used as function return type

Quote:
>Hello,
>Pls help , I am always puzzled by the following problem.
>Say I design a function "char *called(void)" to return a pointer to
>characters
>as follows:

>char *called(void)
>{
>   char sentence[1024];

sentence is local to called() and since it is not declared static, it
exists only for the life of called().

Quote:

>    ......

>   return sentence;

As with almost all references to unsubscripted array names (the
exceptions don't apply here), this is converted by the compiler as the
address of the first element of the array (&sentence[0] if you
prefer).  That address is only valid while the  sentence exists.  Once
you return out of called(), your system is entitled to do anything it
wants with this no longer needed memory.  Any attempt to dereference
this address after you return results in undefined behavior.

Quote:
>}

>>From the perspevtive of the calling function, say "void calling()" as
>folows:

>void calling()
>{
>   char *line;

>   line=called();

I'm not 100% certain whether simply assigning the value to a pointer
is undefined but any attempt to dereference line is definitely
undefined.

Quote:
>}

>inside the calling function, I may use a pointer to characters to be
>assigned the returning pointer from the called function. Now, this

This assertion is true only if the pointer being returned by the
function points to memory still owned by your program.  In the example
you provide, the pointer points to memory you don't own because that
memory  was for an automatic variable whose life was limited to the
function called().

Quote:
>means a pointer in the calling function holding an address of a local
>area(variable), i.e, "sentence", in the called function. Is this

And this is not true.  The returned pointer points to nowhere since
the local variable does not exist any more.

Quote:
>allowed or will cause trouble? I thought the local varible "sentence"
>in the called function will be perish once the execution sequence is
>out of  that called function, which implies the character pointer
>varible I used in the calling function, i.e., "line", pointing to a
>perished local area.

Yes and yes.  It did perish but you are still trying to point to it.

Quote:

>If I call the "called" function 10 time and use an array of pointers
>to hold
>all the returned addresses from the function "called", am I pointing
>to 10
>different local copyies of the perishing local variable "sentence"?

You can compare the different pointers (but only for equality).
Whether any two of them are equal is irrelevant since none of them
point to usable storage.

<<Remove the del for email>>
--



Sat, 19 Mar 2005 22:01:50 GMT  
 problem about pointer used as function return type

Quote:

> Pls help , I am always puzzled by the following problem.
> Say I design a function "char *called(void)" to return a pointer to
> characters
> as follows:

> char *called(void)
> {
>    char sentence[1024];

>     ......

>    return sentence;
> }

> >From the perspevtive of the calling function, say "void calling()" as
> folows:

> void calling()
> {
>    char *line;

>    line=called();
> }

> inside the calling function, I may use a pointer to characters to be
> assigned the returning pointer from the called function. Now, this
> means a pointer in the calling function holding an address of a local
> area(variable), i.e, "sentence", in the called function. Is this
> allowed or will cause trouble?

It will cause trouble, because, as you say yourself: line no longer
points to valid memory. In most implementations, the memory for
sentence[] will still be around on the stack, but it is free for reuse
by whatever function is called next.

Quote:
> If I call the "called" function 10 time and use an array of pointers
> to hold
> all the returned addresses from the function "called", am I pointing
> to 10
> different local copyies of the perishing local variable "sentence"?

In the simple case of just calling called() 10 times in a row, most
implementations will give you 10 times the same pointer; but there is no
guarantee for it.
--



Sat, 19 Mar 2005 22:02:08 GMT  
 problem about pointer used as function return type
in comp.lang.c.moderated i read:

Quote:
>char *called(void)
>{
>   char sentence[1024];
>   return sentence;
>}
>If I call the "called" function 10 time and use an array of pointers to
>hold all the returned addresses from the function "called", am I pointing
>to 10 different local copyies of the perishing local variable "sentence"?

it may be that all 10 values are identical, or it may be that they are all
different, or some combination, but no matter their value it is certain
that they are all invalid and any attempt to dereference will invoke
undefined behavior.

there are two ways this function can be made valid without adding a
parameter:

  char *called(void) { static char sentence[1024]; /**/ return sentence; }
or
  char *called(void) { char *sentence=malloc(1024); /**/ return sentence; }

--
bringing you boring signatures for 17 years
--



Sat, 19 Mar 2005 22:02:12 GMT  
 problem about pointer used as function return type
in comp.lang.c.moderated i read:

Quote:
>it is not generally safe to assume that therefore the last-stored
>value of the local variable is still stored there, as the stack
>space may be reused by the calling function after the return from
>the called function.

perhaps implicitly due to a signal, or on some architectures regular
interrupt activity (something which the standard doesn't discuss but
which often exists) having nothing to do with your application.

--
bringing you boring signatures for 17 years
--



Mon, 21 Mar 2005 08:13:04 GMT  
 
 [ 11 post ] 

 Relevant Pages 

1. Pointer to function returning pointer to function returning...

2. Pointer as function return type?

3. Return type of pointer to a function

4. Question about signal()/pointers to functions that return pointers to functions

5. Help!!, Error when using __stdcall on a function returning a pointer

6. problem returning pointer from function

7. Can function returning pointer return negative integers?

8. Type of function returning function.

9. Returning Pointer To Pointer From Function

10. C++ function pointers versus C function pointer problem

11. Function returning a function-pointer - how to prototype ?

12. Declaring static function returning pointer to extern function

 

 
Powered by phpBB® Forum Software