Click on image to see enlargment

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

            bug815.cpp

1    #include <stdio.h>
2
3    typedef const char *PtrChar;
4    typedef PtrChar *PtrPtrChar;
5 
6    PtrPtrChar message( PtrChar a, PtrChar b )
7        {
8        PtrPtrChar p = (PtrPtrChar) new (char *)[10];
9        p[0] = a; p[1] = b;
10       return p;
11       }
12
13   int main()
14       {
15       PtrPtrChar mc = message( "Merry", "Christmas" );
16       PtrPtrChar hny = message( "Happy", "New Year" );
17       printf( "%s %s\n", mc[0], mc[1] );
18       printf( "%s %s\n", hny[0], hny[1] );
19       return 0;
20       }

Our attempt to wish everyone a Merry Christmas, though syntactically correct, has a serious flaw. Can you find it?


bug815.cpp lint Output

--- Module:   bug815.cpp
                                                _
    PtrPtrChar p = (PtrPtrChar) new (char *)[10];
bug815.cpp(8) : Warning 416: Likely creation of out-of-bounds pointer (10
    beyond end of data) by operator '[' [Reference: file bug815.cpp: line 8]
                                                _
    PtrPtrChar p = (PtrPtrChar) new (char *)[10];
bug815.cpp(8) : Info 815: Arithmetic modification of unsaved pointer
bug815.cpp(8) : Warning 415: Likely access of out-of-bounds pointer (10 beyond
    end of data) by operator '[' [Reference: file bug815.cpp: line 8]
                                                _
    PtrPtrChar p = (PtrPtrChar) new (char *)[10];
bug815.cpp(8) : Info 826: Suspicious pointer-to-pointer conversion (area too small)

Reference Manual Explanation

815   Arithmetic modification of unsaved pointer  -- An allocation expression 
      (malloc, calloc, new) is not immediately assigned to a variable but is 
      used as an operand in some expression.  This would make it difficult to
      free the allocated storage.  For example:

                p = new X[n] + 2;

      will elicit this message.  A preferred sequence is:

                q = new X[n];
                p = q+2;

      In this way the storage may be freed via the custodial pointer q.

      Another example of a statement that will yield this message is:

                p = new (char *) [n];

      This is a gruesome blunder on the part of the programmer. It does NOT 
      allocate an array of pointers as a novice might think.  It is parsed as:

                p = (new (char *)) [n];
      which represents an allocation of a single pointer followed by an index into 
      this 'array' of one pointer.  

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

Previous Bug - Bug #809 - November 2004

[ new ] 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 2006, Gimpel Software, All rights reserved.