c++ - 当我尝试删除指针时我的程序崩溃了

标签 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;
}

我希望删除数组的元素,然后删除指向该数组的指针,但是当我运行它时,我得到了标准的 Windows 错误噪音并且我的程序卡住,直到我 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

还可以考虑针对您的情况使用 vector 或唯一指针。

关于c++ - 当我尝试删除指针时我的程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54436291/

相关文章:

C - 将字符串(句子)转换为字符串列表

c++ - 编译器错误C2541- 'delete' : delete : cannot delete objects that are not pointers

c++ - 何时调用删除运算符(operator)?

c++ - 如何避免 C++ 中两个库的变量/函数冲突

c++ - 为什么 ranges::split_view 不是双向范围?

C++ 概念 访问公共(public)方法

c++ - 调试读/写字符串到二进制文件

c++ - 如何使用 "new"而不是 malloc 分配内存?

c - 为什么指针 + 1 实际上加 4

c++ - C++中非指针数组的删除