【发布时间】:2018-07-22 04:44:45
【问题描述】:
我试图找出在下面的程序中将delete pointerstatement 放在哪里。我想清除pointer指向的内存空间,以避免内存泄漏。似乎无论我把它放在哪里,我都会收到一条错误消息:
main(8282,0x7fff95d823c0) malloc: *** error for object 0x7fff582d3960: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
我不确定如何解决这个问题。任何帮助表示赞赏。
完整代码:
#include <iostream>
#include <vector>
using namespace std;
int main() {
//initialize vector
vector<int> historyValues;
//initialize pointer and int variable
int *pointer;
pointer = new int;
pointer = 0;
int currentValue;
//make pointer point to the address of currentValue
pointer = ¤tValue;
//increment pointer by 1 for a total of 10 times.
//since pointer is pointing at currentValue, currentValue should change also.
//push back the current value of currentValue into the vector.
for (int i = 0; i < 10; i++) {
*pointer += 1;
historyValues.push_back(currentValue);
}
//print final results
cout << "currentValue: " << currentValue << endl;
cout << "*pointer: " << *pointer << endl;
cout << "History of integers stored in currentValue: ";
for (int i = 0; i < historyValues.size(); i++) {
cout << historyValues[i] << " ";
}
cout << endl;
cout << "Program finished" << endl;
return 0;
}
【问题讨论】:
-
请注意,C++ 没有动态变量之类的东西。
标签: c++ pointers memory-leaks delete-operator