malat
malat

Reputation: 12490

gcc warning flag for bogus comparison

I am searching for the right warning flag to use with gcc to detect something like:

#include <stdlib.h>
#include <stdio.h>
int main()
{
  const size_t n = (size_t)-1;
  for( unsigned int i = 0; i < n; ++i ) /* use `unsigned char` if you want */
    {
    printf( "%d\n", i );
    }
  return 0;
}

I tried:

$ gcc -Wsign-conversion -Wconversion -pedantic -Wsign-compare -W -Wall -Wextra -std=c99  t.c 

What happened is that I have been modifying an existing code, that uses unsigned int for memory block size. The code starting failing with larger file. So I need to check I did not miss any remaining left over.

EDIT:

Just discovered -Wtype-limits but again this is not working for me

Upvotes: 1

Views: 240

Answers (2)

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

You are asking the compiler to detect that the condition is always true at run-time. This is barely within its possibilities in this case, because the reason it is always true is that one side is constant and the other is limited by the unsigned int type. I am glad that you found a g++ flag that did it, but if the value of variable n was provided in a different file, or not typed as const, for instance, the compiler may be unable to detect that the condition remains true.

You may also consider using a static analyzer that spends more time than a compiler on the detection of what may and may not happen at run-time. One open-source C analyzer is Frama-C:

function does not reach return

In the screenshot, the statements in red have been detected as unreachable.

The open-source version only works well if the programs makes limited use of library functions, but even so, it can extract information that does not appear in g++'s warnings.

Upvotes: 1

malat
malat

Reputation: 12490

Ok, found out the trick, you need to use the c++ compiler instead:

$ g++ -Wextra  t.c
t.c: In function ‘int main()’:
t.c:6: warning: comparison is always true due to limited range of data type

with:

$ g++ --version
g++ (Debian 4.4.5-8) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 0

Related Questions