首页 > 解决方案 > 当我尝试删除指针时我的程序崩溃了

问题描述

每当我尝试删除指针时,我都会收到“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 中进行调试。

标签: c++pointersdelete-operator

解决方案


您正在分配一个对象 ( 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

还可以考虑为您的案例使用向量或唯一指针。


推荐阅读