Click on image to see enlargment

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

            bug1572.cpp

1    #include <stdio.h>
2
3    int &f( int k )
4        {
5        static int &r = k;
6        return r;
7        }
8
9    int main()
10       {
11       int &a = f( 12 );
12       int &b = f( 13 );
13
14       printf( "a = %d, b = %d\n", a, b );
15       return 0;
16       }

With one compiler this prints 12, 12 and with another it prints 13, 13. Neither compiler issues a complaint. What's wrong?


bug1572.cpp lint Output

--- Module:   bug1572.cpp (C++)
                     _
    static int &r = k;
bug1572.cpp(5) : Warning 1572: Initializing a static reference variable with an
    auto variable 'k'

Reference Manual Explanation


1572   Initializing a static reference variable with an auto variable 'Symbol'  -- A
       static variable has a lifetime that will exceed that of the auto variable that
       it has been bound to.  Consider

             void f( int n ) { static int& r = n; ... }

       The reference r will be permanently bound to an auto variable n. The lifetime of
       n will not extend beyond the life of the function.  On the second and subsequent
       calls to function f the static variable r will be bound to a non-existent entity.


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


Previous Bug - Bug #438 - March 2009

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 2009, Gimpel Software, All rights reserved.