From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 15175 invoked by alias); 9 Oct 2013 10:02:10 -0000 Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org Received: (qmail 15166 invoked by uid 89); 9 Oct 2013 10:02:10 -0000 Authentication-Results: sourceware.org; auth=none X-Spam-SWARE-Status: No, score=-2.2 required=5.0 tests=AWL,BAYES_00,FREEMAIL_FROM,RCVD_IN_DNSWL_LOW,SPF_PASS autolearn=ham version=3.3.2 X-HELO: mail-vc0-f179.google.com Received: from mail-vc0-f179.google.com (HELO mail-vc0-f179.google.com) (209.85.220.179) by sourceware.org (qpsmtpd/0.93/v0.84-503-g423c35a) with (AES128-SHA encrypted) ESMTPS; Wed, 09 Oct 2013 10:02:09 +0000 Received: by mail-vc0-f179.google.com with SMTP id ht10so328929vcb.24 for ; Wed, 09 Oct 2013 03:02:07 -0700 (PDT) MIME-Version: 1.0 X-Received: by 10.220.186.202 with SMTP id ct10mr5081215vcb.14.1381312926894; Wed, 09 Oct 2013 03:02:06 -0700 (PDT) Received: by 10.52.178.71 with HTTP; Wed, 9 Oct 2013 03:02:06 -0700 (PDT) In-Reply-To: References: Date: Wed, 09 Oct 2013 10:02:00 -0000 Message-ID: Subject: Re: Crazy compiler optimization From: vijay nag To: Jonathan Wakely Cc: "gcc-help@gcc.gnu.org" Content-Type: text/plain; charset=ISO-8859-1 X-IsSubscribed: yes X-SW-Source: 2013-10/txt/msg00011.txt.bz2 On Wed, Oct 9, 2013 at 3:24 PM, Jonathan Wakely wrote: > On 9 October 2013 10:36, vijay nag wrote: >> Hello GCC, >> >> I'm facing a wierd compiler optimization problem. Consider the code >> snippet below >> >> #include >> >> int printChar(unsigned long cur_col, unsigned char c) >> { >> char buf[256]; >> char* bufp = buf; >> char cnt = sizeof(buf) - 2; /* overflow in implicit type conversion */ >> unsigned long terminal_width = 500; >> >> while ((cur_col++ < terminal_width) && cnt) { >> *bufp++ = c; >> cnt--; >> } > > >> Basically the crash here is because of elimination of the check in the >> if-clause "&& cnt" which is causing stack overrun and thereby SIGSEGV. >> While standards may say that the behaviour is >> undefined when an unsigned value is stored in a signed value, > > Standards do not say that. 254 cannot be presented in a char if char > is a signed type, so it's an overflow, which is undefined behaviour. > Storing an unsigned value that doesn't overflow is OK. > >> can a >> language lawyer explain to me why GCC chose to eliminate code >> pertaining to cnt considering it as dead-code ? > > cnt is initialized to -2 (after an overflow) and then you decrement it > so it gets more negative. The "&& cnt" condition will never be false, > because cnt starts non-zero and gets further from zero, so will never > reach zero. Alright that is perfectly valid behaviour. Why does compiler consider it to be a unsigned type at optimization level zero ? i.e. I see a wrap around after -128 to 128 ?