整数内存分配/释放
Integer memory allocation/deallocation
收到以下错误:
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;
相关文章:
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 调用析构函数以释放动态分配的内存
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 错误:malloc:对象 0x7f9edf504080 的 *** 错误:未分配正在释放的指针
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 释放动态分配的内存时是否需要执行此额外步骤
- 整数内存分配/释放
- 我是否需要在 c++ 中从本地指针中释放分配的内存?
- 释放分配给大量矢量的内存的最有效方法是什么?
- 为什么要在释放分配给该对象的内存之前调用该对象的默认析构函数?
- 在崩溃时释放分配的指针的正确方法
- 为什么要正确释放分配的内存
- 如何在C++中释放分配的静态值
- 删除链表中的节点后释放分配的空间
- 是否可以从C++释放分配的内存输出
- 释放分配给二维向量的内存
- 如何释放分配的参数
- 从数组中移除一个元素并释放分配给它的内存
- 我可以在glTexImage2D调用后释放分配给图像的内存吗?