Struct c++中的内存泄漏

Memory Leak in Struct C++

本文关键字:内存 泄漏 c++ Struct      更新时间:2023-10-16

我有一个这样的结构,

struct int * ramp_output (int * L10)
{
    int * r;
    r = L10;
    return(r);
}

我应该从L10和r中释放内存吗?

首先,您的代码将无法在那里编译多余的"struct"。删除它,我们可以回答你的问题:这取决于参数是如何分配的,但在任何情况下你都应该只做一次。

int main()
{
    int a[]  = { 1, 1, 1 };
    int i    = 42;
    int* pi1 = &i;
    int* pi2 = new int[10];
    int* pi3 = new int(42);
    std::vector<int> v( 10 );
    std::shared_ptr<int> sp( new int(42) );
    int* r1 = ramp_output(a);
    int* r2 = ramp_output(&i);
    int* r3 = ramp_output(pi1);
    int* r4 = ramp_output(pi2);
    int* r5 = ramp_output(pi3);
    int* r6 = ramp_output(&v[0]);
    int* r7 = ramp_output(sp.get());
    // what to dealloc? Only these
    delete [] pi2; // or delete [] r4; but not both!
    delete pi3;    // or delete    r5; but not both!
}

结构体不接受参数或返回值。如果你从代码中删除"struct",这将是一个有效的(尽管微不足道)函数:它只是返回一个指针,指向它的参数是一个指针。您不需要或不想释放任何内存

作为一般规则,在c++中唯一需要释放内存的时候是使用"new"关键字创建内存的时候。例如

int * test = new int;

在这种情况下,指针"test"指向堆上的一个整数,"某人"应该删除它。谁负责删除它取决于你的程序设计,如果你把指针传递给其他函数,而它们存储/使用它的副本,你不应该删除它。

至于你的示例代码,它真的没有任何意义,所以你必须告诉我们你到底想做什么来帮助解决这个问题。