0

Hopefully I don't dumb down my code too much...

Index::Index() : m_first(""), m_count(0)
{
    m_ll = new LinkedList;
}
void TestClass::testMethod()
{
    if (getIndex(i).getCount() != 0)
    {
        //do stuff
    }
}
Index TestClass::getIndex(int num) const
{
    return m_index[num];
}
Index::~Index()
{
    delete m_ll;
}

This is the code that's really involved in the crash. When I enter testMethod, I have m_index[num], which contains a pointer to m_ll. They're completely valid. After it returns m_index[num], it goes into the destructor even though m_index[num] is still in use and because of this, my program crashes. I don't understand why the destructor would be called so early.

Michael Blake
  • 993
  • 1
  • 8
  • 18
  • 2
    Show much more of your code. Compile with all warnings & debug info (`g++ -Wall -Wextra -g`) then use the debugger (`gdb`) and perhaps [valgrind](http://valgrind.org/) – Basile Starynkevitch Oct 21 '15 at 07:27
  • The `Index` returned by `getIndex` will be destroyed at the end of `if` condition expression. Maybe you want to return a reference instead? Maybe your copy constructor is broken? – TartanLlama Oct 21 '15 at 07:30
  • Here are ideas on what parts of your code to include in your question: [mcve] – anatolyg Oct 21 '15 at 08:02

1 Answers1

2

The dtor calls delete, getIndex returns by value. My crystal ball tells me that Index::Index() calls new but Index::Index(Index const&) does not.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Sorry that I didn't include Index::Index(). I just added that, but you're right. The only thing is, I don't have a copy constructor at all. I'm assuming I'll need one that that calls new? – Michael Blake Oct 21 '15 at 08:02
  • @MichaelBlake Yes. This is called [Rule of Three](http://stackoverflow.com/q/4172722/509868). Short version [here](http://stackoverflow.com/a/14105409/509868). – anatolyg Oct 21 '15 at 08:03
  • @MichaelBlake: You have a copy ctor; `getIndex` wouldn't have compiled otherwise. However, it's the **default** memberwise copy ctor which just copies the pointer. That means you get 2 identical Index objects, both of which will call `delete` on the same pointer. – MSalters Oct 21 '15 at 08:10