整数内存allocation/deallocation

Integer memory allocation/deallocation

出现以下错误:

malloc:对象 0x7ffee85b4338 的 *** 错误:未分配正在释放的指针

我以为我分配和解除分配正确,但我一定没有。我做错了什么?它将以零错误和零警告进行编译,但不会在内存释放后打印出最后一条语句(完成)。

查看下面的源代码。感谢任何帮助。

#include <iostream>
using namespace std;

int main(){

    int numOne, numTwo, numThree;

    cout << "When prompted please enter a whole number." << endl;

    //obtain user input for numbers and store to integer variables
    cout << "\nEnter a number: ";
        cin >> numOne;
    cout << "Enter another number: ";
        cin >> numTwo;
    cout << "Enter a third number: ";
        cin >> numThree;

    //print out user's entered numbers as stored in variables
    cout<< "\nThe numbers you entered currently stored as variables are: ";
    cout << numOne << ", " << numTwo << " and " << numThree << endl;

    //create pointers and allocate memory
    int* pointerOne   = new int;
    int* pointerTwo   = new int;
    int* pointerThree = new int;

    //store location of variables to pointers
    pointerOne   = &numOne;
    pointerTwo   = &numTwo;
    pointerThree = &numThree;

    //print out user's entered numbers as stored in pointers
    cout<< "The numbers you entered currently stored as pointers are: ";
    cout << *pointerOne << ", " << *pointerTwo << " and " << *pointerThree << endl;


    //alter user's numbers to show that pointers alter variables
    cout << "\nNOTICE: Incrementing entered values by one! ";
        *pointerOne   = *pointerOne + 1;
        *pointerTwo   = *pointerTwo + 1;
        *pointerThree = *pointerThree + 1;
    cout << "....COMPLETE!" << endl;

    //print out user's entered numbers as stored in variables
        cout<< "\nThe numbers you entered incremented by one shown using variables:  ";
        cout << numOne << ", " << numTwo << " and " << numThree << endl;

    //deallocate memory
    cout << "\nWARNING: Deallocating pointer memory! ";
        delete pointerOne;
        delete pointerTwo;
        delete pointerThree;
    cout << "....COMPLETE!" << endl;

}

您可以将用户的输入存储到您为其分配内存的指针变量中,然后使用指针来操作它们的值:

int *numOne, *numTwo, *numThree;
numOne = new int;
numTwo = new int;
numThree = new int;

int *pointerOne, *pointerTwo, *pointerThree;
pointerOne = numOne;
pointerTwo = numTwo;
pointerThree = numThree;

cout << "\nEnter a number: ";
cin >> *numOne; // You can use cin >> *pointerOne;
cout << "Enter another number: ";
cin >> *numTwo; // You can use cin >> *pointerTwo;
cout << "Enter a third number: ";
cin >> *numThree; // You can use cin >> *pointerThree;

cout << "\nNOTICE: Incrementing entered values by one! ";
*pointerOne++;
*pointerTwo++;
*pointerThree++;
cout << "....COMPLETE!" << endl;

delete numOne;
delete numTwo;
delete numThree;