整数内存分配/取消分配

时间:2018-09-30 18:04:00

标签: c++ memory memory-management allocation

出现以下错误:

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

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

请参见下面的源代码。任何帮助表示赞赏。

#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;

}

1 个答案:

答案 0 :(得分:0)

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

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;