Returning address of a local variable.

Sep 22, 2009 at 7:22am
I was reading Object oriented programming using c++ by Ira Pohl, when I came across following piece of code.

1
2
3
4
5
6
7
8
my_string& operator+(const my_string& a, const my_string& b)
{
   my_string* temp = new my_string(a.len + b.len);
   
   strcpy(temp->s, a.s);
   strcpy(temp->s, b.s);
   return *temp;
}


I remember reading somewhere that, it is an error to return the address of a local variable. Can anyone tell me how above code wroks? Isn't it wrong to return the address of temp?
Sep 22, 2009 at 7:29am
They are not returning the address of temp. *temp means, get the value stored at the address pointed by temp. They have actually de-referenced the pointer.


EDIT: And the memory pointed by temp is on heap, so it does not follow the scope rules, you will have to explicitly de-allocate it using delete.
Last edited on Sep 22, 2009 at 7:30am
Sep 22, 2009 at 7:56am
I'm still confused. What is the return type here? Is it "my_string" ? What does "my_string&" return type means?

Here what is returned? value of temp or a reference to temp?

Thanks.
Sep 22, 2009 at 11:14am
my_string& means a 'reference of type my_string'
Sep 22, 2009 at 1:19pm
The local variable in the function is a pointer to a my_string.

What is being returned from the function is a reference to the my_string pointed to by the local variable.

That is quite a bizarre piece of code. Screams memory leak to me.

Sep 22, 2009 at 10:14pm
Yes, it has a memory leak. It uses new to allocate something on the heap, then returns it like something referenced. At no time does the caller know it is supposed to delete it.
Sep 23, 2009 at 5:13am
For the record - I thought I would check out how such a peice of code slipped past the Author/and editor of that book - And I found this on the Author's homepage at:
http://users.soe.ucsc.edu/~pohl/

Notice about halfway down the page in the Acknowledgment section.
Last edited on Sep 23, 2009 at 5:14am
Sep 23, 2009 at 5:35am
Thanks guys for clarifying this piece of code.

@guestgulkan

Thanks for linking author's homepage. I can use this to check for other corrections.
Topic archived. No new replies allowed.