编辑:Pastebin 链接到底部的全部代码
在我的 CS215 课程中,我获得了一个名为 String215 的类,它是一个基本的字符串类,用于帮助理解动态内存分配和 char 数组的指针运算。
该课程以非常基本的骨架形式提供给我,其中包含原型但没有实现,以及用于测试我的实现的测试函数。我不能在这个作业中使用任何 C 字符串函数。
程序中麻烦的部分是 append 函数,它只是将参数 string215 对象附加到当前 string215 对象的末尾。
// Add a suffix to the end of this string. Allocates and frees memory.
void string215::append(const string215 &suffix)
{
char *output = new char[str_len(data)+suffix.length()+1];
for(int x = 0; x < str_len(data); x++) {
*output = *data;
output++;
data++;
}
for(int x = 0; x < suffix.length(); x++) {
*output = suffix.getchar(x);
output++;
}
*output = '\0';
output -= (str_len(data)+suffix.length()+1);
delete[] data;
data = output;
}
这部分代码在测试函数的第 13 次测试中进行测试,如下所示:
string215 str("testing");
...
// Test 13: test that append works in a simple case.
curr_test++;
string215 suffix("123");
str.append(suffix);
if (strcmp(str.c_str(), "testing123") != 0) {
cerr << "Test " << curr_test << " failed." << endl;
failed++;
}
这是附加类的描述:
将后缀添加到此字符串的末尾。分配一个新的更大的数组;将旧内容(后跟后缀)复制到新数组;然后释放旧数组并更新指向新数组的指针。
我的程序在附加函数执行结束时中止并显示错误消息:
Debug Assertion Failed!
Program: [Source path]\dbgdel.cpp
Line: 52
Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)
...
Abort || Retry || Ignore
我相当肯定这与我非常糟糕的内存管理有关。我知道这没什么好做的,但是我已经为此苦苦挣扎了几个小时,似乎无法弄清楚。
这是该程序的 .cpp 和 .h 文件的 pastebin
string215.cpp:http ://pastebin.com/Xh2SvDKJ
string215.h:http ://pastebin.com/JfAJDEVN
非常感谢任何帮助!
谢谢,生浆果