我很难解决我认为是双重自由的问题

时间:2019-06-06 11:54:05

标签: c++

我正在尝试创建一个作为类成员的链表向量。 Valgrind显示没有内存泄漏,但是在程序结束时还会产生无效的free()/ delete / delete [] / realloc()错误。

我试图通过为链表编写析构函数,复制构造函数和复制赋值运算符来解决此问题。我相信这些已正确实施。我还尝试了将链接列表添加到成员向量的各种方法(引用,指针,智能指针),似乎都无法解决问题。

#include "lists.h"

lists::lists() {

}

void lists::newList() {
  int size, value;
  cout << "Please specify size of this list" << endl;
  cin >> size;
  shared_ptr<list> new_list(new list);
  //list *new_list = new list();
  for (int i = 0; i < size; i++) {
    cout << "Enter value for node " << i + 1 << endl;
    cin >> value;
    new_list->pushBack(value);
  }
  list_storage.push_back(new_list);
  //delete new_list;
}

void lists::deleteList() {

}

void lists::display() {
  for (int i = 0; i < list_storage.size(); i++) {
    list_storage[i]->display();
  }
}

#include "list.h"

list::list() {
  head = NULL;
}

list::list(const list& list) {
  head = NULL;
  node *current = head;
  while (current != NULL) {
    this->pushBack(current->data);
    current = current->next;
  }
}

list& list::operator=(const list& rhs) {
  list temp(rhs);
  swap(temp.head, head);
  return *this;
}

list::~list() {
  if (head != NULL) {
    node *current = head;
    while (current != NULL) {
      node *next = current->next;
      delete current;
      current = next;
    }
    delete head;
  }
}

这是valgrind的输出:

==15967== Invalid free() / delete / delete[] / realloc()
...
==15967== HEAP SUMMARY:
==15967==     in use at exit: 0 bytes in 0 blocks
==15967==   total heap usage: 9 allocs, 10 frees, 74,856 bytes allocated
==15967== 
==15967== All heap blocks were freed -- no leaks are possible
==15967== 
==15967== For counts of detected and suppressed errors, rerun with: -v
==15967== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

1 个答案:

答案 0 :(得分:11)

看看您的析构函数:

 new Client
                {

                    ClientId =  "openIdConnectClient",
                    ClientName = "Implicit Client Application Name",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowedScopes = new List<string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "role",
                        "customAPI.write"
                    },

                    RedirectUris = new List<string>{ "http://localhost:56582/signin-oidc" },
                    PostLogoutRedirectUris = new List<string>{ "http://localhost:56582" },
                   // FrontChannelLogoutUri = "http://localhost:56582/signout-oidc"

                }

进入循环,您删除list::~list() { if (head != NULL) { node *current = head; while (current != NULL) { node *next = current->next; delete current; current = next; } delete head; } } ,它是第一次迭代时的current。循环后,再次删除head->双重释放。