简体   繁体   中英

C++ deleting pointers from vector causes heap error

I have a vector of pointers to objects of my base class and then I store objects from derived class in it. The way I add pointers is quite obvious

std::vector<Element*> mvGates;
...
mvGates.push_back(new Node(x, y));

And when my program is about to be closed those pointers are freed in 'for' loop

 for (int i=0; i<mvGates.size(); ++i)
 {
     delete mvGates[i];
 }

At this line my debugger (I'm using Qt Creator) is showing a few lines like that:

Heap block at 14E50F50 modified at 14E50F84 past requested size of 2c
Invalid address specified to RtlFreeHeap( 00030000, 14E50F58 )

What can be the cause, what am I doing wrong? I know that I haven't showed you full code, since it's quite long, but maybe it is enough to tell me my mistake. Probably you will recommend me using smart pointers. I think I will do it but that doesn't answer my question - what can be wrong with this code.

EDIT: It was a very simple mistake, you couldn't have noticed it here. In Node class I've declared some_type array[0];

And I've been using it as a 2 elements array. I don't know why it didn't cause a SIGSEGV but it was the thing that caused heap error.

Your std::vector contains pointers to Element class instances but your are filling it using Node class instances. Since the compiler does not complain we can safely assume that Node extends Element.

The problem is that when you delete these elements you are referring to them as Elements. Unless you are overriding correctly Element destructor the delete operation will call Element::~Element() and not Node::~Node()

In your class definition make sure that the destructor is virtual:

class Element{
   virtual ~Element(){
      //Element cleanup
   }

   //....
};

In your code, your are visiting each object in vector by using index, and you are deleting them. However, besides what "Pierluigi" said (the virtual ~ problem), shouldn't you visit each object and delete them by using iterator rather than by using index directly?

You had mistaken in the incremental part. Its i++ you need not ++i.

If you use ++i, it will increment before looping into for loop so at the iterator number it is referring mvGates[i] which actually doesn't exist. Only vector ranges from 0 to length-1.

for (int i=0; i<mvGates.size(); i++)
{
    delete mvGates[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM