我一直在尝试解决这个问题一段时间,并决定是时候从外部角度看待问题了。我已经尽可能多地用谷歌搜索,从我读到的类似问题中,这(我认为)与我分配的内存少于所需的内存有关。我已经多次检查我的代码,但找不到我的错误在哪里。
我的教授编写了一个打印函数,并且仅在调用该函数时才会出现问题,因此我将搜索范围缩小到我编写的这个函数。
IntStore& IntStore::operator=(const IntStore& rhs)
{
if(this != &rhs)
{
int* newData = new int[rhs.capacity];
int* newFreq = new int[rhs.capacity];
for(int i=0; i < rhs.used; i++)
{
newData[i] = rhs.data[i];
newFreq[i] = rhs.freq[i];
}
delete [] data;
delete [] freq;
data = newData;
freq = newFreq;
capacity = rhs.capacity;
used = rhs.used;
}
return *this;
}
他的打印功能如下:
void print_to_cout(IntStore src)
{
// NOTE:
// - first for-loop below looks silly but is purposely added
// - don't try to remove/disable when doing the assignment
// - Why is it added?
for (int i = 1; i < 2; ++i)
{
src = src;
IntStore copy1;
copy1 = src;
}
int countDist = src.countDistinct();
for (int i = 1; i <= countDist; ++i)
cout << setw(5) << src.valAt(i);
cout << endl;
cout << " (freq)";
for (int i = 1; i <= countDist; ++i)
cout << setw(5) << src.freqAt(i);
cout << endl;
}
当我运行程序时,这是我得到的:
*** glibc detected *** ./a2: free(): invalid next size (fast): 0x0000000005714010 ***
任何帮助表示赞赏并提前感谢。
我包括构造函数以显示代码的更具体部分以帮助解决我的问题。至于打印功能。我不知道为什么它是这样写的。主 cpp 文件中的所有内容均由教授创建,不可编辑。我们所做的唯一编辑是对 Instore.cpp 文件。标题也是预制的。
#include "IntStore.h"
#include <iostream>
#include <cstdlib>
#include <cassert>
using namespace std;
void IntStore::resize(int new_capacity)
{
if(new_capacity < used)
new_capacity = used;
if(new_capacity < 1)
new_capacity = 1;
capacity = new_capacity;
int* newData = new int[capacity];
int* newFreq = new int[capacity];
for(int i=0; i < used; i++)
{
newData[i] = data[i];
newFreq[i] = freq[i];
}
delete [] data;
delete [] freq;
data = newData;
freq = newFreq;
}
IntStore::IntStore(int init_capacity) : capacity(init_capacity), used(0)
{
if(capacity < 1)
capacity = DEFAULT_CAPACITY;
data = new int(capacity);
freq = new int(capacity);
}
IntStore::IntStore(const IntStore& src) : capacity(src.capacity),
used(src.used)
{
data = new int(capacity);
freq = new int(capacity);
for(int i = 0; i < used; i++)
{
data[i] = src.data[i];
freq[i] = src.freq[i];
}
}
IntStore::~IntStore()
{
delete [] data;
delete [] freq;
}
这是打印功能的情况:
case 'p': case 'P':
objectNum = get_object_num();
switch (objectNum)
{
case 1:
if ( is1.empty() )
cout << " is1: (empty)" << endl;
else
{
cout << " is1: (data)";
print_to_cout(is1);
}
break;
case 2:
if ( is2.empty() )
cout << " is2: (empty)" << endl;
else
{
cout << " is2: (data)";
print_to_cout(is2);
}
break;
case 3:
if ( is3.empty() )
cout << " is3: (empty)" << endl;
else
{
cout << " is3: (data)";
print_to_cout(is3);
}
}