0 Replies - 7349 Views - Last Post: 10 April 2012 - 05:15 AM Rate Topic: -----

#1 olibenu  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 45
  • View blog
  • Posts: 538
  • Joined: 31-December 08

Returning local object's address

Posted 10 April 2012 - 05:15 AM

Sweet is the memory of past troubles. I've forgotten who said that.
It started with a little laziness.
I had a function which returned a pointer to a list and got tired of checking for NULL.
So instead of
if (somelist == NULL)
cout << "somelist has 0 items";
else cout << "somelist has " << somelist->size() << " items";

I decided to use
cout << "somelist has " << somelist->size() << " items";

Making the HUGE mistake of changing the function from
list<int>* obj = NULL
obj = new list<int>;
/*sum stuff*/
return obj;

list<int> obj
/*sum stuff*/
return &obj;

I tested it with valgrind and it worked though warning about returning a local variable's address
Running outside valgrind gave segmentation errors!
And my code was calling functions from 2 or so shared libraries, I just
couldn't think of where the errors came from (the nightmare!).

Lesson learnt (or relearnt ;-)): never, ever, return a function's variable address.
lesson not learnt: why would valgrind not trip over it?

Is This A Good Question/Topic? 0
  • +

Page 1 of 1