整数内存分配/释放

Integer memory allocation/deallocation

本文关键字:释放 分配 内存 整数      更新时间:2023-10-16

收到以下错误:

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

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

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;