Solution

The ValueContainer::myInt pointer is always initialized to the address of a local variable, namely the i passed to the createContainer(int) method. Local variables are allocated on the stack and are deallocated as soon as their scope is closed. In this case, the i variable local to createContainer is deallocated at the end of the createContainer method, hence the pointer which has been stored in the ret pointer to ValueContainer object points to an unused area of the stack. Chances are this stack area will be overwritten when functions are called and returned from, so the output is unpredictable.

There are several ways to fix this bug. The most direct is to replace the statement \fbox{\tt ret->set(\&i);} with \fbox{\tt ret->set(new
int(i));} , and to add the statement \fbox{\tt delete theInt;} in the class destructor.

A more meaningful bugfix would involve recognizing that the semantics of the class is wrong. Set/get pairs should behave with the same data, and the fact that the integer data within the class (theInt) has a name which does not remind of a pointer are strong hints that the real bug was to design a class that stores an integer pointer when all that was needed was simply an integer. Thus the ``correct correction'' is to make all changes so that theInt is an integer variable instead of a pointer to integer.

Leo Liberti 2008-01-12