From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 17111 invoked by alias); 9 May 2012 11:48:03 -0000 Received: (qmail 17087 invoked by uid 22791); 9 May 2012 11:48:03 -0000 X-SWARE-Spam-Status: No, hits=-4.3 required=5.0 tests=ALL_TRUSTED,AWL,BAYES_00,KHOP_THREADED X-Spam-Check-By: sourceware.org Received: from localhost (HELO gcc.gnu.org) (127.0.0.1) by sourceware.org (qpsmtpd/0.43rc1) with ESMTP; Wed, 09 May 2012 11:47:50 +0000 From: "rui.maciel at gmail dot com" To: gcc-bugs@gcc.gnu.org Subject: [Bug c/50476] Warn of pointer set to object whose lifetime is limited Date: Wed, 09 May 2012 11:50:00 -0000 X-Bugzilla-Reason: CC X-Bugzilla-Type: changed X-Bugzilla-Watch-Reason: None X-Bugzilla-Product: gcc X-Bugzilla-Component: c X-Bugzilla-Keywords: diagnostic X-Bugzilla-Severity: enhancement X-Bugzilla-Who: rui.maciel at gmail dot com X-Bugzilla-Status: UNCONFIRMED X-Bugzilla-Priority: P3 X-Bugzilla-Assigned-To: unassigned at gcc dot gnu.org X-Bugzilla-Target-Milestone: --- X-Bugzilla-Changed-Fields: Message-ID: In-Reply-To: References: X-Bugzilla-URL: http://gcc.gnu.org/bugzilla/ Auto-Submitted: auto-generated Content-Type: text/plain; charset="UTF-8" MIME-Version: 1.0 Mailing-List: contact gcc-bugs-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-bugs-owner@gcc.gnu.org X-SW-Source: 2012-05/txt/msg00993.txt.bz2 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=50476 --- Comment #3 from Rui Maciel 2012-05-09 11:47:49 UTC --- (In reply to comment #2) > I think it is only undefined behaviour to access the pointer after the > life-time of y has finished, however, the following probably isn't, no? > > void g() > { > ... > *x = 2; > ... > } As x hasn't been declared at that point, it should throw a compiler error. If x was a global pointer which was declared previously then a similar problem would arise. Take, for example, the following code: #include int *x = 0; void f(void) { int a = 2; x = &a; } int main(void) { f(); printf("Value: %d\n",*x); return 0; } Again, x is set to the address of a local variable, which is then accessed at a point where the local variable's lifetime has ended. This behaviour is explicitly left undefined in ISO 9899:1999 6.2.4 2. Therefore, it would be nice if the compiler warned about that. > void f() > { > ... > x = &y; > ... > g(); > ... > x = NULL; > } > > The C/C++ FE cannot distinguish between these two cases. > > Do you have a suggestion about how to implement this? >>From the user's point of view, it would be nice if the compiler warned if an object was being accessed after its lifetime. This should happen at least when the user explicitly specified the use of a standard which stated that this behaviour is undefined. Granted, this might not be an easy thing to implement. As I don't have any knowledge on gcc's inner workings, I'm not in a position to suggest how this might be done.