Square
Square

Reputation: 45

C++ Is it a memory leak? Pointer to array alocated dynamicaly in another function

Quick question. Will this leak and why/ why not?

int main()
{
    int array[] = {1,2,3};
    doStuff(array);
    return 0;
}

when doStuff will do something like this

void doStuff(int * arr)
{
    // ...
    arr = new int [50];
    // ...
}

EDIT for @Scott Hunter I think it won't leak because array points to memory on stack and I've never heard of memory leaking from stack, but on the other hand i kinda lose any link to this memory.

EDIT2 My problem was I was thinking that changing arr in doStuff address will change array in main as well but it won't.

Upvotes: 0

Views: 99

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Yes it will leak, since you don't call delete [] arr; anywhere inside of doStuff().

Note that you don't even change the int array[]; declared outside of the function.
All you are doing is to change a copy of that pointer that was passed as by value parameter.


As an aside recommenation:

Don't use raw pointers and raw arrays in c++. Rather use a std::vector<int> for your case, and forget about dynamic memory management at all.

Upvotes: 7

Vittorio Romeo
Vittorio Romeo

Reputation: 93264

doStuff takes a copy of the array pointer. Setting arr to something else inside the body of doStuff will not modify the original array value in main.

Therefore, unlesss you call delete[] arr inside doStuff, your code will leak.

Upvotes: 5

Related Questions