Bug++ of the Month



April 01, 1998
URL:http://www.drdobbs.com/bug-of-the-month/184416488

April 1998/Bug++ of the Month


Defining the lifetime of objects in C++ doesn’t sound like a very exciting subject. I suspect most WDJ readers don’t spend much time worrying about it. But I can assure you, the members of the ISO C++ standardization committee spent a substantial amount of time considering this topic.

Consider the simple code fragment shown below. This routine has a for loop that creates a temporary Bar object on each pass through the loop. The obvious questions are: when does each temporary object get constructed, and when does each temporary object get destroyed?

class Bar {
  //...
};

bool Baz( Bar& b );

int Foo()
{
    for ( int i = 0 ; i < 10 ; i++ ) {
        cout << “Baz returned: “;
        if ( Baz( Bar(i) ) )
            cout << "Success\n";
        else
            cout << "Failure\n";
    }
    //...
}

The creation question in this case is fairly simple: the compiler must generate a temporary Bar() just before it calls Baz() each time in the loop. However, you can imagine many different destruction strategies a program could use. You could destroy the temporary when the if statement completes, or when the for loop exits. You could destroy them when Foo() exits. You could even let the temporaries hang around until the program exits.

As it happens, the ISO standard dictates that the temporaries are normally destroyed as the last step in evaluating the expression that uses the temporary. So in the code shown above, each temporary copy of Bar() is created, passed to function Baz(), then destroyed immediately after Baz() returns.

Knowing the rules here is critical in C++. Creating and destroying objects in C programs simply meant allocating or releasing storage space, and usually didn’t have a big effect on programs. In C++, constructors can do just about anything, such as allocating and freeing key system resources. You really need to have a good understanding of when this happens in your programs. And with the ratification of the C++ standard, the required behavior is now specified.

Borland’s Lifetime Troubles

One of WDJ’s many readers from Down Under, John Burger, noted a problem Borland has with the lifetime of objects under slightly complicated conditions. My demonstration program for John’s bug is shown in apr98.cpp (Listing 1). This program has a static data object named Baz that is local to function Bar(). Local static objects are normally constructed when execution passes through their declaration, and are not destroyed until the program exits.

What complicates the situation here is that the constructor for Baz needs to create two temporary objects of its own. So the first time through this loop, you should see the Foo constructor called three times, once for each of the two temporaries, and once again for the creation of Baz. The two temporary objects should then be immediately destroyed, but Baz should not be destroyed until the program exits.

The next time Bar() is called, no Foo constructors should be called. Baz has already been created, so its constructor doesn’t need to be invoked. Likewise, there wouldn’t be much point in creating the two temporaries, since they aren’t needed.

But as the output shown below indicates, Borland’s 32-bit 5.x compiler gets a little confused about what it should and should not destroy, and when it should be destroyed. The first time through Bar(), the three objects are constructed more or less as expected. Only two destructors are called, but not without some trouble. By my reading, the standard indicates that ordinary temporary variables are supposed to be destroyed in reverse of their creation order. The compiler does just the opposite.

Calling Bar() for the first time...
constructing Foo(2, temp)
constructing Foo(1, temp)
constructing Foo(3, static)
Baz = 3, static
destroying Foo(2, temp)
destroying Foo(1, temp)

Calling Bar() for the second time...
Baz = 3, static
destroying Foo(4199312, H»@)
destroying Foo(0, 0_c)

Terminating...
destroying Foo(3, static)

The trouble really starts on the second pass through Bar(). In this case, the constructor for Baz is not called, since it is static and has already been created. But when the routine exits, the compiler mistakenly tries to destroy the two temporaries! As previously shown in this column, calling the destructor for an invalid object can be disastrous. Imagine a destructor that updates a database or flushes cached data to disk, and you can see how nasty this can get.

Borland’s Response

Borland’s John Wiegley investigated the bug and provided this reply:

We have confirmed that this is a problem with destructor cleanup existing in Borland C++ 5.02 and C++ Builder 1.0, which has been fixed in C++ Builder 3.0. With the newest version of the compiler, the program works as anticipated in the program’s comments.

Borland has announced that Borland C++ will no longer be a separate product. Your upgrade path from Borland C++ v5.02 is C++ Builder 3.0.

Summary

John Burger is to be commended for tracking down this truly nasty bug. In addition to our adulation, John gets a free WDJ t-shirt and our deep appreciation. If you run into a C++ bug that you would like to expose to the light of day, please pass it on to us at [email protected], and we’ll try to use it in a future column.

Correction to Last Month’s Column

The inline code for changes to the <deque> header contained a typographical error. The second line of the void pop_back() section should read:

--_Size;

and not

—_Size;

as printed.

Mark Nelson is a partner in Addisoft Consulting (www.addisoft.com), located in Addison, Texas. Addisoft provides programming services for a wide variety of C and C++ program development tasks. You can reach Mark at [email protected], or at http://web2.airmail.net/markn.

Get Source Code

April 1998/Bug++ of the Month/Listing 1

Listing 1: apr98.cpp — Borland’s temporary destructor bug

// This program demonstrates a couple of interesting
// problems with Borland C++ 5.x.  Subroutine Bar()
// contains a static object Baz, which should be constructed
// the first time the routine is called, and destroyed
// when the program exits.  This much works properly.
//
// The static object, Baz, is constructed using a pair
// of temporary instances of Foo.  The ISO standard dictates
// that the lifetime of these temporaries should expire at
// the end of the statement construucting Baz.  However,
// viewing the program output shows that the temporaries
// are not destroyed until Bar() exits. The should also
// be destroyed in the reverse of the order they were
// constructed.
//
// Much worse, however, is the error that occurs the second
// time that Bar() is called.  Since the static object, Baz,
// is not constructed the second time through the routine,
// the two temporaries are not created.  However, the routine
// still attempts to destroy the non-existent routines upon
// exit.  This is very bad!  Note that the bad char * value
// in the non-existent temporaries may cause your version of
// the program to crash.
//
//  Build this program using the following command line:
//
//   bcc32 apr98.cpp
//

#include <iostream.h>

class Foo {
public:
    Foo( int val, char *tag ) {
        m_val = val;
        m_tag = tag;
        cout << "constructing Foo("
             << m_val
             << ", "
             << m_tag
             << ")\n";
    }
    ~Foo() {
        cout << "destroying Foo("
             << m_val
             << ", "
             << m_tag
             << ")\n";
    }
    int m_val;
    char *m_tag;
};

ostream &operator <<( ostream &os, const Foo &f )
{
   return os << f.m_val << ", " << f.m_tag;
}

int operator +( const Foo &lhs, const Foo &rhs )
{
    return lhs.m_val + rhs.m_val;
}

void Bar()
{
    static Foo Baz =
        Foo( Foo( 1, "temp" ) + Foo( 2, "temp" ), "static" );
    cout << "Baz = " << Baz << endl;
}

int main()
{
    cout << "\nCalling Bar() for the first time...\n";
    Bar();
    cout << "\nCalling Bar() for the second time...\n";
    Bar();
    cout << "\nTerminating...\n";
    return 0;
}
//End of File
April 1998/Bug++ of the Month

Bug++ of the Month

Mark Nelson


Defining the lifetime of objects in C++ doesn’t sound like a very exciting subject. I suspect most wdj readers don’t spend much time worrying about it. But I can assure you, the members of the ISO C++ standardization committee spent a substantial amount of time considering this topic.

Consider the simple code fragment shown below. This routine has a for loop that creates a temporary Bar object on each pass through the loop. The obvious questions are: when does each temporary object get constructed, and when does each temporary object get destroyed?

class Bar {
  //...
};

bool Baz( Bar& b );

int Foo()
{
    for ( int i = 0 ; i < 10 ; i++ ) {
        cout << “Baz returned: “;
        if ( Baz( Bar(i) ) )
            cout << "Success\n";
        else
            cout << "Failure\n";
    }
    //...
}

The creation question in this case is fairly simple: the compiler must generate a temporary Bar() just before it calls Baz() each time in the loop. However, you can imagine many different destruction strategies a program could use. You could destroy the temporary when the if statement completes, or when the for loop exits. You could destroy them when Foo() exits. You could even let the temporaries hang around until the program exits.

As it happens, the ISO standard dictates that the temporaries are normally destroyed as the last step in evaluating the expression that uses the temporary. So in the code shown above, each temporary copy of Bar() is created, passed to function Baz(), then destroyed immediately after Baz() returns.

Knowing the rules here is critical in C++. Creating and destroying objects in C programs simply meant allocating or releasing storage space, and usually didn’t have a big effect on programs. In C++, constructors can do just about anything, such as allocating and freeing key system resources. You really need to have a good understanding of when this happens in your programs. And with the ratification of the C++ standard, the required behavior is now specified.

Borland’s Lifetime Troubles

One of wdj’s many readers from Down Under, John Burger, noted a problem Borland has with the lifetime of objects under slightly complicated conditions. My demonstration program for John’s bug is shown in apr98.cpp (Listing 1). This program has a static data object named Baz that is local to function Bar(). Local static objects are normally constructed when execution passes through their declaration, and are not destroyed until the program exits.

What complicates the situation here is that the constructor for Baz needs to create two temporary objects of its own. So the first time through this loop, you should see the Foo constructor called three times, once for each of the two temporaries, and once again for the creation of Baz. The two temporary objects should then be immediately destroyed, but Baz should not be destroyed until the program exits.

The next time Bar() is called, no Foo constructors should be called. Baz has already been created, so its constructor doesn’t need to be invoked. Likewise, there wouldn’t be much point in creating the two temporaries, since they aren’t needed.

But as the output shown below indicates, Borland’s 32-bit 5.x compiler gets a little confused about what it should and should not destroy, and when it should be destroyed. The first time through Bar(), the three objects are constructed more or less as expected. Only two destructors are called, but not without some trouble. By my reading, the standard indicates that ordinary temporary variables are supposed to be destroyed in reverse of their creation order. The compiler does just the opposite.

Calling Bar() for the first time...
constructing Foo(2, temp)
constructing Foo(1, temp)
constructing Foo(3, static)
Baz = 3, static
destroying Foo(2, temp)
destroying Foo(1, temp)

Calling Bar() for the second time...
Baz = 3, static
destroying Foo(4199312, H»@)
destroying Foo(0, 0_c)

Terminating...
destroying Foo(3, static)

The trouble really starts on the second pass through Bar(). In this case, the constructor for Baz is not called, since it is static and has already been created. But when the routine exits, the compiler mistakenly tries to destroy the two temporaries! As previously shown in this column, calling the destructor for an invalid object can be disastrous. Imagine a destructor that updates a database or flushes cached data to disk, and you can see how nasty this can get.

Borland’s Response

Borland’s John Wiegley investigated the bug and provided this reply:

We have confirmed that this is a problem with destructor cleanup existing in Borland C++ 5.02 and C++ Builder 1.0, which has been fixed in C++ Builder 3.0. With the newest version of the compiler, the program works as anticipated in the program’s comments.

Borland has announced that Borland C++ will no longer be a separate product. Your upgrade path from Borland C++ v5.02 is C++ Builder 3.0.

Summary

John Burger is to be commended for tracking down this truly nasty bug. In addition to our adulation, John gets a free wdj t-shirt and our deep appreciation. If you run into a C++ bug that you would like to expose to the light of day, please pass it on to us at [email protected], and we’ll try to use it in a future column.

Correction to Last Month’s Column

The inline code for changes to the <deque> header contained a typographical error. The second line of the void pop_back() section should read:

--_Size;

and not

—_Size;

as printed.

Mark Nelson is a partner in Addisoft Consulting (www.addisoft.com), located in Addison, Texas. Addisoft provides programming services for a wide variety of C and C++ program development tasks. You can reach Mark at [email protected], or at http://web2.airmail.net/markn.

Get Source Code

April 1998/Bug++ of the Month/Listing 1

Listing 1: apr98.cpp — Borland’s temporary destructor bug

// This program demonstrates a couple of interesting
// problems with Borland C++ 5.x.  Subroutine Bar()
// contains a static object Baz, which should be constructed
// the first time the routine is called, and destroyed
// when the program exits.  This much works properly.
//
// The static object, Baz, is constructed using a pair
// of temporary instances of Foo.  The ISO standard dictates
// that the lifetime of these temporaries should expire at
// the end of the statement construucting Baz.  However,
// viewing the program output shows that the temporaries
// are not destroyed until Bar() exits. The should also
// be destroyed in the reverse of the order they were
// constructed.
//
// Much worse, however, is the error that occurs the second
// time that Bar() is called.  Since the static object, Baz,
// is not constructed the second time through the routine,
// the two temporaries are not created.  However, the routine
// still attempts to destroy the non-existent routines upon
// exit.  This is very bad!  Note that the bad char * value
// in the non-existent temporaries may cause your version of
// the program to crash.
//
//  Build this program using the following command line:
//
//   bcc32 apr98.cpp
//

#include <iostream.h>

class Foo {
public:
    Foo( int val, char *tag ) {
        m_val = val;
        m_tag = tag;
        cout << "constructing Foo("
             << m_val
             << ", "
             << m_tag
             << ")\n";
    }
    ~Foo() {
        cout << "destroying Foo("
             << m_val
             << ", "
             << m_tag
             << ")\n";
    }
    int m_val;
    char *m_tag;
};

ostream &operator <<( ostream &os, const Foo &f )
{
   return os << f.m_val << ", " << f.m_tag;
}

int operator +( const Foo &lhs, const Foo &rhs )
{
    return lhs.m_val + rhs.m_val;
}

void Bar()
{
    static Foo Baz =
        Foo( Foo( 1, "temp" ) + Foo( 2, "temp" ), "static" );
    cout << "Baz = " << Baz << endl;
}

int main()
{
    cout << "\nCalling Bar() for the first time...\n";
    Bar();
    cout << "\nCalling Bar() for the second time...\n";
    Bar();
    cout << "\nTerminating...\n";
    return 0;
}
//End of File

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.