Click on image to see enlargment

PC-lint/FlexeLint Output | Reference Manual Explanation | Home


1    #include <stdio.h>
3    class X
4        {
5        public:
6            int *px;
7            X( int init )
8                { px = new int; *px = init; }
9            ~X() { delete px; }
10       };
12   void print( X x )
13       {  printf( "%d\n", *x.px );  }
15   int main() {
16       X x(15); print( x );
17       X y(16); print( x );  print( y );
18       return 0;
19       }

The output the programmer expected to see was 15, 15, and 16. Instead, he got 15, 16 and 16. What went wrong?

bug1733.cpp lint Output

--- Module:   bug1733.cpp (C++)
            { px = new int; *px = init; }
bug1733.cpp(8) : Info 1732: new in constructor for class 'X' which has no
    assignment operator 
bug1733.cpp(8) : Info 1733: new in constructor for class 'X' which has no copy
bug1733.cpp(10) : Info 1712: default constructor not defined for class 'X'

Reference Manual Explanation

1733   new in constructor for class Symbol which has no copy constructor
       -- Within a constructor for the cited class, there appeared a
       new.  However, no copy constructor was declared for this class.
       Presumably, because of the new, some class member (or members)
       points to dynamically allocated memory.  Such memory is not
       treated properly by the default copy constructor.  Normally a
       custom copy constructor would be needed.  [12, Item 11]

We'd like to thank Frederic Vlyminckx of Belgium for submitting this additional explanation about Bug #1733.

Since there is no copy constructor defined, the call to 'print' will not place a deep copy onto the stack. The local copy used during execution of 'print' will have its member variable px point to the same int on the heap as the px of object x. When the 'print' function exits, the destructor is applied to the local copy, hereby destroying the dynamically allocated int (which both x and the local copy have in common). The px of x is now pointing to non allocated memory. When object y is created afterwards, the compiler will reallocate this released memory for y, making the px of y and the px of x both pointing to the same int. This is why the program prints 15, 16 & 16.

If you have comments or questions about this bug, please post them to our   Discussion Forum

Previous Bug - Bug #560 - August 2011

Use our Interactive Demo to Run FlexeLint on our Bugs of the Month

PC-lint/FlexeLint - Product Overview

Home | Contact | Order

PC-lint and FlexeLint are trademarks of Gimpel Software
Copyright 2011, Gimpel Software, All rights reserved.