auto_ptr as pass by value to functions – you are going to face a crash.

12 05 2008


Memory leaks are our nightmare and auto_ptr’s are used for making our life easier which does automatic memory deletion. If a pointer is assigned to an auto_ptr, it will be deleted when the auto_ptr went out of scope. But use this automatic deletion carefully, especially while passing it as function arguments by value. You are going to face a crash!


The problem is “owership”. Every auto_ptr holds an ownership flag. when an auto_ptr is assigned to another auto_ptr, the ownership flag is transfered from first to second. And only the auto_ptr with ownership flag enabled, can delete the resource. This method is used to avoid multiple deletion of the same pointer kept by several auto_ptrs. There will be only one owner auto_ptr at a time.

Now when you pass the auto_ptr by value, actually, you are passing the owner ship to the stack variable of the called function. Now the stack parameter will become the owner of your pointer and when the function returns, the auto_ptr in stack will be destructed and since its the owner, it will delete your passed pointer. When you access you main auto_ptr, then you’ll probably get a crash!!! See the code snippet for an e.g.

// Function which receives auto_ptr as value.
void ToUpper( auto_ptr<CString> pString )
{
    // Shows the messageBox.
    pString->MakeUpper();
}

// The one and only Main.
void main()
{
    // An auto_ptr which holds a CString.
    auto_ptr<CString> pString(
        new CString(_T("Hello AutoPtr")));

    // Make the string upper case by
    // passing it as value.
    ToUpper( pString );

    // At this point, your CString is already
    // been deleted by the stack variable in function.

    // Now change the string to Lower and face the crash!!!
    pString->MakeLower();
}


You can make the situation safe by passing by reference. While doing so, only a reference is passed to the stack variable and hence the ownership remains in you main auto_ptr itself.


Targeted Audience – Intermediate.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: