程序不会移过删除
Program wont move past delete
所以我无法弄清楚为什么我的程序在清除循环中的删除语句处停止。它不会崩溃,它只是不会执行或给我任何类型的错误。
我已经仔细检查了我正在删除一个数组并需要括号,并验证它是有效的新内存。如果它由析构函数调用或显式调用,它将不起作用
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>
将为您提供您在此处尝试实现的所有功能(
相关文章:
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 在unique_ptr<>中使用自定义删除程序 (curl_formfree())
- 如何从 CLion 的运行窗口中删除程序项目路径
- shared_ptr的删除程序是否存储在自定义分配器分配的内存中?
- 用于unique_ptr的有状态自定义删除程序
- 为什么unique_ptr不能阻止自定义删除程序的切片?
- std::shared_ptr 在空指针上调用非默认删除程序
- std::unique_ptr 和自定义删除程序
- 如何避免多个删除程序 lambda
- 如何使用lambda和函数作为unique_ptr的自定义删除程序
- std::unique_ptr,自定义删除程序和类型更改
- shared_ptr<EVP_PKEY> EVP_PKEY_free作为自定义删除程序会导致堆损坏
- 使用自定义删除程序返回unique_ptr的 nullptr 失败
- 对 Direct3D11 对象上使用 std::shared_ptr 的自定义删除程序
- 为shared_ptr但遇到错误指定自定义删除程序
- 为什么unique_ptr无法推断出删除程序的类型?
- 删除程序的调用上下文
- unique_ptr、自定义删除程序和零法则
- std::在C++中设置删除程序不起作用
- 带有自定义删除程序错误的 c++ 唯一指针