尝试删除指针时程序崩溃

时间:2019-01-30 08:34:35

标签: c++ pointers delete-operator

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

1 个答案:

答案 0 :(得分:1)

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

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