c++ - 当我尝试删除指针时我的程序崩溃了
问题描述
每当我尝试删除指针时,我都会收到“Windows 错误噪音”,然后我的程序就会冻结但从未正式崩溃。
void addIngredient(char ** & ingredients, int & numOfIng)
{
char * str = nullptr;
char **tempArr = new char*[numOfIng];
numOfIng++;
//init tempArr to nullptr
for (int i = 0; i < numOfIng; i++)
{
tempArr[i] = nullptr;
}
//set the new array to the old array
for (int i = 0; i < numOfIng - 1; i++)
{
tempArr[i] = new char;
tempArr[i] = ingredients[i];
}
delete [] ingredients;
//point the old array to the new one
ingredients = tempArr;
//add the new element to the end of the old array
cout << "What new ingredient would you like to add? ";
str = new char[25];
cin >> str;
ingredients[numOfIng - 1] = str;
delete str;
//method tought to us in class on how to clear array and what is being pointers within the array
for (int i = 0; i < numOfIng; ++i)
{
delete [] tempArr[i]; //Freezes here
}
delete [] tempArr;
}
我希望删除数组的元素,然后删除指向该数组的指针,但是当我运行它时,我得到标准窗口错误噪音,我的程序冻结,直到我 ctrl+c 控制台窗口。编码新手,所以请不要让我太难受。不确定这是否重要,但我正在使用 Visual Studio 2017 并在 x86 中进行调试。
解决方案
您正在分配一个对象 ( char
),然后忘记了新对象:
tempArr[i] = new char;
tempArr[i] = ingredients[i];
您要做的是设置数据:
tempArr[i] = new char;
*(tempArr[i]) = *(ingredients[i]);
这样新角色就不会丢失。
您还有另一个问题,当您这样做时delete [] ingredients;
,您并没有删除基础指针。然后你稍后删除临时子数组(delete [] tempArr[i]
),所以你应该做的是:
for (int i = 0; i < numOfIng; ++i)
{
delete ingredients[i]; // Note that I remove the [], as you have only new char, not new char[1]
}
之后没有删除,因为新ingredients
的正在使用这些“旧” tempArr
。
还可以考虑为您的案例使用向量或唯一指针。
推荐阅读
- sql-server - Ansible win_dsc 无法使用 SqlServerDsc 安装 SqlServer
- java - Rabbitmq 死信交换不起作用导致无限重试
- cordova - 带有 wkwebview 插件的 Cordova ios - window.open(url, "_system") 不起作用
- python-3.x - 如何在python中显示所有caffe层的名称?
- jenkins - 在 Jenkins 管道中的给定阶段超时后继续执行后续阶段
- python - 如果数据范围很大,如何查看数据的分布
- java - 给定 Chronology,Java Time API 从 sql Timestamp 获取偏移量
- ruby-on-rails - 除了仅验证确切的字符串之外,如何验证 Rails 形式的对象的唯一性?
- flutter - Flutter - 动态改变容器颜色
- c++ - 如何首先包含与第 3 方文件冲突的 CMake 生成的 config.h?