简体   繁体   English

内存释放C ++

[英]Memory deallocation c++

I obviously misunderstood something using delete . 我显然误用了delete Why is this program filling up my memory? 为什么这个程序会填满我的记忆?

void f(int* x){
    x = new int[42];
}

int main(){
    while(true){
        int* x;
        f(x);
        delete[] x;
    }
    return 0;
}

How can I free the memory I allocated in f from inside the main function? 如何从main函数内部释放在f分配的内存?

You are not actually modifying the x variable in the outer function. 您实际上并没有在外部函数中修改x变量。
To do that, you have either to rely on the returned value of f : 为此,您必须依靠f的返回值:

int* f(){
    return new int[42];
}

int main(){
    while(true){
        int* x = f();
        delete[] x;
    }
    return 0;
}

Or to pass the variable x by reference: 或通过引用传递变量x

void f(int*& x){
    x = new int[42];
}

int main(){
    while(true){
        int* x;
        f(x);
        delete[] x;
    }
    return 0;
}

Or to use a pointer to pointer as an argument to f : 或者使用指向指针的指针作为f的参数:

void f(int** x){
    *x = new int[42];
}

int main(){
    while(true){
        int* x;
        f(&x);
        delete[] x;
    }
    return 0;
}

And so on... 等等...

There are memory leaks in the function 函数中存在内存泄漏

void f(int* x){
    x = new int[42];
}

You allocate memory but never free it. 您分配内存,但永远不会释放它。 Function parameters are local variables of the function. 函数参数是函数的局部变量。 The function deals with a copy of the original pointer. 该函数处理原始指针的副本。 Any changes of the copy do not influence on the original argument. 复制的任何更改都不会影响原始参数。

And mpreover the program has undefined behaviour because pointer x is not initialized. 并且mpreover程序具有未定义的行为,因为指针x未初始化。

int main(){
    while(true){
        int* x;
        ^^^^^^
        f(x);
        delete[] x;
    }
    return 0;
}

You need to pass the original pointer by reference. 您需要通过引用传递原始指针。 So the function should be defined like 所以功能应该像

void f(int* &x){
    x = new int[42];
}

and called like 叫像

f(x);

or defined like 或定义为

void f(int* *x){
    *x = new int[42];
}

and called like 叫像

f( &x );

Pass the parameter by reference. 通过引用传递参数。 You're passing it by value. 您正在通过价值传递它。

So what you might want to do is consider constructing a functor/class/struct that uses RAII... 因此,您可能要考虑构建使用RAII的函子/类/结构。

By this I mean how the standard library handles a lot of allocations. 我的意思是说标准库如何处理大量分配。

struct A {
A(){/*allocate mem*/}
~A(){/*deallocate mem*/}
}

For your particular function, 对于您的特定功能,

void f(int** x);

is most likely the signature you want. 是您想要的签名。 This will allow you to modify the array through the pointer to it. 这将允许您通过指向数组的指针来修改数组。 Though... I still recommend not doing this... the reason is what about if you decide to allocate a bunch of arrays? 虽然...我仍然建议不要这样做...原因是如果您决定分配一堆数组呢? Does the main method take responsibility for deallocating memory? 主要方法是否负责分配内存?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM