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?
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.
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.
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.