Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C++ handle cleanup of pointers passed as arguments?

I've been doing some research on how C++ handles pointers passed as arguments, but haven't been able to find a solid 'yes/no' answer to my question so far.

Do I need to call delete/free on them, or is C++ smart enough to clear those on it's own?

I've never seen anyone call delete on passed pointers, so I'd assume that you don't need to, but I'd like to know if anyone knows any situations when doing it is actually required.

Thanks!

like image 783
Phillip Elm Avatar asked Dec 03 '22 05:12

Phillip Elm


1 Answers

The storage used for pointers passed as arguments will be cleaned up. But the memory that they point to will not be cleaned up.

So, for instance:

void foo(int *p)  // p is a copy here
{
    return;
    // The memory used to hold p is cleared up,
    // but not the memory used to hold *p
}

int main()
{
    int *p = new int;
    foo(p);   // A copy of p is passed to the function (but not a copy of *p)
}

You will often hear people talk about "on the heap" and "on the stack".* Local variables (e.g. arguments) are stored on the stack, which is automatically cleaned up. Data allocated using new (or malloc) is stored on the heap, which is not automatically cleaned up.


* However, the C++ standard doesn't talk about "stack" and "heap" (these are actually implementation-specific details). It uses the terminology "automatic storage" and "allocated storage", respectively.
like image 147
Oliver Charlesworth Avatar answered Feb 18 '23 09:02

Oliver Charlesworth