This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Counter intuitively, asserts hurt gcc static dataflow analysis.


Consider the following code....

#include <stdio.h>

void func( char * a, int i)
{
   printf( "%c\n", a[i]);
}

int main( int argc __attribute__((unused)), char * argv[]
__attribute__((unused)))
{
   int i = 10;
   char a[] = "abc";

   func( a, i);

   return 0;
}

Compile with..
   gcc  -W -Wall -Wextra -o b b.c
and no warnings.

Run it, it runs, but prints garbage.

Compile with
   gcc  -O3 -W -Wall -Wextra -o b b.c
And gcc correctly points out the error....

b.c: In function ‘main’:
b.c:5:21: warning: ‘*((void *)&a+10)’ is used uninitialized in this
function [-Wuninitialized]
    printf( "%c\n", a[i]);
                     ^
b.c:11:9: note: ‘a’ was declared here
    char a[] = "abc";

Hey! That's quite Smart of gcc, it analysed across the function boundary!
(I have observed on large projects gcc is now astoundingly clever about
this!)

Now counter intuitively, adding asserts make things worse!

Consider....

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void func( char * a, int i)
{
   assert( i < 4);
   printf( "%c\n", a[i]);
}

int main( int argc __attribute__((unused)), char * argv[]
__attribute__((unused)))
{
   int i = 10;
   char a[] = "abc";

   func( a, i);

   return 0;
}

Compiling without optimizations again produces no warnings, but at run time
you, correctly....

a: a.c:7: func: Assertion `i < 4' failed.

Compilation aborted (core dumped) at Fri May  4 10:52:26

But compile with ...
gcc  -O3 -W -Wall -Wextra -o a a.c
...now results in NO warnings!

ie. Although gcc _knows_ the assert  _will_ trigger at run time... it can't
tell me at compile time anymore.

ie. Counter intuitively, adding asserts and error checks to my code has
made me less safe.

I can't help feel there must be some cunning Cthulhu inspired way of
utilizing what gcc clearly knows, to fail the assertion at compile time!

Any suggestions?

-- 
John Carter
Phone : (64)(3) 358 6639
Tait Electronics
PO Box 1645 Christchurch
New Zealand

-- 
This Communication is Confidential. We only send and receive email on the

basis of the terms set out at www.taitradio.com/email_disclaimer 
<http://www.taitradio.com/email_disclaimer>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]