程序不会移过删除

Program wont move past delete

本文关键字:删除 程序      更新时间:2023-10-16

所以我无法弄清楚为什么我的程序在清除循环中的删除语句处停止。它不会崩溃,它只是不会执行或给我任何类型的错误。

我已经仔细检查了我正在删除一个数组并需要括号,并验证它是有效的新内存。如果它由析构函数调用或显式调用,它将不起作用

int main()
{
darray DA1;
DA1.Add("Hello");
DA1.Add("Good Morning");
return 0;
}
void Add(const char * string)
{
char ** temp = new char *[m_count + 1];
for (int i = 0; i < m_count; ++i)
temp[i] = m_array[i];
temp[m_count] = new char[strlen(string)];
strcpy(temp[m_count], string);
delete[] m_array;
m_array = temp;
m_count++;
}
void Purge()
{
for (int i = 0; i < m_count; ++i)
{
delete [] m_array[i];
m_array[i] = nullptr;
}
delete[] m_array;
m_array = nullptr;
m_count = 0;
}

我希望它通过 2d 动态数组删除每个数组,然后删除最终数组。

这些行包含一个错误:

temp[m_count] = new char[strlen(string)];
strcpy(temp[m_count], string);

。因为您分配了strlen(string)个字节,但忽略了分配字符串末尾所需的 NUL 终止符所需的额外字节。 因此,您的strcpy()命令在分配的数组末尾写入一个字节,调用未定义的行为。 您可以通过将其更改为以下内容来更正它:

temp[m_count] = new char[strlen(string)+1];
strcpy(temp[m_count], string);

一个单独的说明:即使对于有经验的程序员来说,以这种方式手动管理堆分配也很难正确,所以除非你编写这个程序作为练习来学习如何手动管理堆分配,否则我强烈建议使用std::string(或一些类似的字符串类(而不是 C 风格的字符数组。 您将为自己节省很多不必要的痛苦。 (事实上,我认为std::vector<std::string>将为您提供您在此处尝试实现的所有功能(