c++ - 我的析构函数是否给我这个错误 : *** Error in `./main' : double free or corruption (fasttop):?

标签 c++ linux class destructor

这是我的作业说明: 复制构造函数。复制构造函数应该执行参数对象的深层复制,即它应该构造一个与参数具有相同大小和容量的 IntCollection,并具有参数数据数组的完整拷贝。

赋值运算符 (=)。赋值运算符还应该执行参数对象的深层复制。它必须返回自身(或更有效地返回对自身的引用),以便支持同一行上的多个赋值,例如a = b = c。如果您首先实现赋值运算符,则可以在复制构造函数中使用它,但这不是必需的。

等于运算符 (==)。如果参数对象与接收对象具有相同的大小,并且两个对象的数据数组中的值相同,则“等于”运算符应返回 true。

插入运算符 (<<)。插入运算符应将 int 参数添加到接收 IntCollection 中。功能与 add() 函数完全相同,即将整数添加到集合中。但请注意,该函数必须返回对其自身的引用,以便支持同一行上的多次插入,例如c << 45 << -210。与赋值运算符不同的是,这个返回必须通过引用来完成,因为每次插入实际上都会修改 IntCollection 对象,并且插入是从左到右进行的。

析构函数。当需要更多空间时,函数 add() 调用 addCapacity() 来分配内存。这个程序中没有任何地方用delete[]释放内存,这意味着我们有内存泄漏!添加一个正确处理此问题的析构函数。

添加容量。请注意,addCapacity() 是一个私有(private)成员函数。如果您尝试从类外部调用它,即通过将下面的行添加到 main() 中,会发生什么?

c.addCapacity();

这是我的代码: IntCollection.h:

#ifndef INTCOLLECTION_H
#define INTCOLLECTION_H

// Allocate memory in chunks of ints of this size.
const int CHUNK_SIZE = 5;

class IntCollection
{
  private:
  // The number of ints currently stored in the int
    int size;
  // the total number of elements available for storage
  // in the data array
    int capacity;
  // A pointer to the dynamically allocated data array
    int* data;
  // a private member function to allocate more memory 
  // if necessary
    void addCapacity();
  public:
  // Constructor
    IntCollection();
  // Destructor
    ~IntCollection();
  // Copy constructor:
    IntCollection(const IntCollection &c);

    void add(int value);
    int get(int index);
    int getSize();
    IntCollection& operator=(const IntCollection &c);
    bool operator==(const IntCollection &c);
    IntCollection& operator<<(int value);
};

#endif

IntCollection.cpp:

#include "IntCollection.h"
#include <cstdlib>
#include <iostream>
using namespace std;

IntCollection::IntCollection() 
{
    // Initialize member data to reflect an empty
    // IntCollection
    size = capacity = 0;
    data = NULL;
}

IntCollection::~IntCollection() 
{
    delete [] data;
}

IntCollection::IntCollection(const IntCollection &c) {
    size = c.size;
    capacity = c.capacity;
    data = c.data;

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

void IntCollection::addCapacity() 
{
    // Create a new, bigger buffer, copy the current data to
    // it, delete the old buffer, and point our data
    // pointer to the new buffer
    int *newData;
    data = new int[capacity];
    capacity += CHUNK_SIZE;
    newData = new int[capacity];

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

void IntCollection::add(int value) 
{
    // first, allocate more memory if we need to
    if (size == capacity) 
    {
        addCapacity();
    }
    // Now, add the data to our array and increment size
    data[size++] = value;
}

int IntCollection::get(int index) 
{
    if (index < 0 || index >= size) 
    {
        cout << "ERROR: get() trying to access index out of range.\n";
        exit(1);
    }
    return data[index];
}

int IntCollection::getSize() 
{
    return size;
}

IntCollection &IntCollection::operator=(const IntCollection &c) 
{
    size = c.size;
    capacity = c.capacity;
    data = c.data;

    return *this;
}

bool IntCollection::operator==(const IntCollection &c) 
{
    if ((size == c.size) && (capacity == c.capacity)) 
    {
        for (int m = 0; m < size; m++) 
        {
            if (data[m] == c.data[m]) 
            {
                continue;
            } else 
            {
                return false;
            }
        }
    }
    return true;
}

IntCollection &IntCollection::operator<<(int value) 
{
    add(value);
    return *this;
}

ma​​in.cpp:

#include "IntCollection.h"
#include <iostream>
using namespace std;

int main() 
{
  IntCollection c;

  c.add(45);
  c.add(-210);
  c.add(77);
  c.add(2);
  c.add(-21);
  c.add(42);
  c.add(7);

  for (int i = 0; i < c.getSize(); i++)
  {
    cout << c.get(i) << endl;
  }

  IntCollection d(c);
  for (int i = 0; i < c.getSize(); i++)
  {
    cout << c.get(i) << endl;
  }

  IntCollection e;
  e = c;
  cout << "Testing = Overload" << endl;

  for(int i = 0; i < c.getSize(); i++)
  {
    cout << c.get(i) << endl;
  }

  IntCollection f;
  f<<8<<9<<10;
  cout << "Testing<<Overload" << endl;
  for(int i = 0; i < f.getSize(); i++)
  {
    cout << f.get(i) << endl;
  }

  cout << "Testing == Overload" << endl;

  c.add(10);

  if(f == c)
  {
    cout << "Both objects match" << endl;
  }
  else
  {
    cout << "They don't match" << endl;
  }

  return 0;
}

在我相信我修复了大部分错误之后,我得到以下输出:

*** Error in `./main': double free or corruption (fasttop): 0x0000000000b2ec80 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x70bfb)[0x7ff7e6f70bfb]
/lib/x86_64-linux-gnu/libc.so.6(+0x76fc6)[0x7ff7e6f76fc6]
/lib/x86_64-linux-gnu/libc.so.6(+0x7780e)[0x7ff7e6f7780e]
./main[0x400fa1]
./main[0x400fe2]
./main[0x400aa2]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf1)[0x7ff7e6f202e1]
./main[0x40097a]
======= Memory map: ========
00400000-00402000 r-xp 00000000 08:01 11008976                           /home/runner/main

我不会全部发布,因为它很长。是我的析构函数造成的吗?我不知道如何解决这个问题,也没有遇到过这个错误。

最佳答案

复制构造函数中的这一行可能是问题:

data = c.data;

在该行之后,您有两个对象指向相同数据。这是一个拷贝。

如果其中一个对象被破坏,那么 if 将会删除[]数据,而给另一个对象留下无效的指针。当第二个对象析构函数尝试删除[]数据(再次!)时,它将导致 undefined behavior .

您需要进行深层复制,这是您的作业。这包括内存分配和实际复制数据。

与复制赋值运算符相同。

关于c++ - 我的析构函数是否给我这个错误 : *** Error in `./main' : double free or corruption (fasttop):?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50034580/

相关文章:

c++ - 根据抽象类快速确定子类

c++ - 在 C++ 中将 vector 转换为数组

c# - 从我的 ASPX 页面调用 C# 类

jquery - 添加此 jQuery 后无法取消选中复选框

java - 无法解析android studio中的某些符号

c++ - 将 MinGW 从 4.4.1 更新到 4.7.1 后,SFML 项目将无法运行

c++ - 如何使用 irrlicht 获取鼠标位置?

c - 如何使用clone()让父进程和子进程同时运行?

mysql - 将 Java Web 应用程序与 jboss、mysql 和 activemq 一起打包以进行部署

c - 可以创建通用的 linux 程序吗?