简体   繁体   中英

Push_back method of vector of pointers causes crash C++

I'm trying to add pointers to a vector in C++. As such:

          Puzzle * puzzleStart = new Puzzle();

          std::vector<Puzzle*> OPEN;

          OPEN.push_back(puzzleStart);

The first time a pointer is pushed, there is no problem. The second time, it causes a crash. I'm guessing the issue is the size of the vector, but I don't understand why. Is there anything more to this?

Update: You are right, the problem is elsewhere, I just realized that it occurs while I free the vector of pointer. There is another issue, if the vector contains dupplicates of pointers I think.

   if (OPEN.size()!=0){
       for (int i = 0; i < OPEN.size(); ++i) {
      delete OPEN[i]; // Calls ~object and deallocates *tmp[i]
       }
      OPEN.clear();
       } 

How do i make sure that it doesn't try to erase allready deleted pointers?

You are right, the problem is elsewhere, I just realized that it occurs while I free the vector of pointer. There is another issue, if the vector contains dupplicates of pointers I think.

       if (OPEN.size()!=0){
           for (int i = 0; i < OPEN.size(); ++i) {
          delete OPEN[i]; // Calls ~object and deallocates *tmp[i]
           }
          OPEN.clear();
           } 

How do i make sure that it doesn't try to erase allready deleted pointers?

If the problem is duplication of pointers, you should consider a container that does not allow duplication, such as a set. Eg:

std::set<Puzzle*> s;
Puzzle *puzz = new Puzzle();
auto insert_result = s.insert(puzz);

if(!insert_result.second)
{
    std::cout << "\"puzz\" was a duplication. No insertion made.\n";
}

// More items inserted into s, and used, etc.

for(auto p : s)
    delete p;

s.clear();

When you delete the pointer, set it to nullptr. Deleting a null pointer does not cause a crash.

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