【问题标题】:Where to place delete operator for dynamic variable在哪里放置动态变量的删除运算符
【发布时间】: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 = &currentValue;

    //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


【解决方案1】:

在这个程序中pointer 指代可以释放的动态内存块的唯一位置是在pointer = new int;pointer = 0; 之间如果你在这两行之间移动delete pointer,你会没事的。

那么改变的结果是:

pointer = new int;
delete pointer;
pointer = 0;

但是,您最好删除所有这三行并以 pointer = &amp;currentValue; 开头,因为您的代码从不使用动态分配的 int


另外,您的评论“增量指针”不正确。您正在递增指针的目标,而不是指针。

【讨论】:

  • 我要做的是增加 *pointer 以间接更改 currentValue 的值。如果我摆脱了pointer = new int;pointer = 0,那么不会还有内存泄漏吗?
  • @HernanRazo:如果你取出new int,就不会泄漏。具有自动生命周期的变量,例如currentValue,在函数返回时会自动释放。
  • @Hernan 我怀疑你误解了关于指针的一些事情:1)指针p 持有一个地址实际值 被存储。 2) 您可以使用p 获取/设置地址,或者使用*p 获取/设置地址处的。 3) 您可以动态分配内存(例如使用new)并设置地址。 4) 但这不是设置地址的唯一方法(例如设置p=&lt;address of existing variable&gt;)。 5) 每当您动态分配内存(新)时,您应该在适当时释放它(删除)。 6)如果您在删除前更改了地址,则不能再删除;和泄漏
  • @CraigYoung:我不想在没有首先确保我没有忽略有效问题的情况下重写。既然你说这只是一个可能被误解的问题,我现在要澄清一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
相关资源
最近更新 更多