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

            bug1554.cpp

1     #include <stdio.h>
2     #include <string.h>
3     class X
4         {
5       public:
6         char *p;
7         X( const char *s ) { p = new char[strlen(s)+1]; strcpy(p,s); }
8         X( const X & x ) { p = x.p; }
9         ~X() { delete[] p; }
10        };
11    char *get( X x ) { return x.p; }
12    int main()
13        {
14        X a("hello"); char *worda = get(a);
15        X b("world"); char *wordb = get(b);
16        printf( "%s %s\n", worda, wordb );
17        return 0;
18        }

The class X has a number of flaws, one of which is responsible for the fact that the classical greeting comes up garbled on most compilers. Can you spot the flaw?


bug1554.cpp lint Output

--- Module:   bug1554.cpp
                             _
    X( const char *s ) { p = new char[strlen(s)+1]; strcpy(p,s); }
bug1554.cpp(7) : Info 1732: new in constructor for class 'X' which has no
    assignment operator
                              _
    X( const X & x ) { p = x.p; }
bug1554.cpp(8) : Warning 1554: Direct pointer copy of member 'X::p' within copy
    constructor: 'X::X(const X &)'
    _
    };
bug1554.cpp(10) : Info 1712: default constructor not defined for class 'X'
                               _
char *get( X x ) { return x.p; }
bug1554.cpp(11) : Info 1746: parameter 'x' in function 'get(X)' could be made
    const reference

Reference Manual Explanation

 
1554  Direct pointer copy of member 'Symbol' within copy constructor: 'Symbol'  --
      In a copy constructor a pointer was merely copied rather than recreated with
      new storage. This can create a situation where two objects have the same data
      and this, in turn, causes problems when these objects are deleted or modified.
      For example, the following class will draw this warning:

                class X
                   {
                   char *p;
                   X( const X & x )
                      { p = x.p; }
                   ...
                   };

      Here, member p is expected to be recreated using new or some variant.

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

Previous Bug - Bug #1741 - April 2003

PC-lint/FlexeLint - Product Overview

Home | Contact | Order

PC-lint and FlexeLint are trademarks of Gimpel Software
Copyright 2003, Gimpel Software