Jonas
Jonas

Reputation: 1847

Memory deallocation c++

I obviously misunderstood something using 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?

Upvotes: 2

Views: 111

Answers (4)

rtbaldwin
rtbaldwin

Reputation: 88

So what you might want to do is consider constructing a functor/class/struct that uses 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?

Upvotes: -1

skypjack
skypjack

Reputation: 50540

You are not actually modifying the x variable in the outer function.
To do that, you have either to rely on the returned value of 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:

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:

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

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

And so on...

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

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.

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 );

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

Pass the parameter by reference. You're passing it by value.

Upvotes: 1

Related Questions