[vox-tech] loop never exits!

Brian Lavender brian at brie.com
Wed Apr 21 11:51:22 PDT 2010


On Wed, Apr 21, 2010 at 10:19:34AM -0700, Harold Lee wrote:
> I've used static analysis tools before, and they find many many more
> bugs than compilers do.
> 
> http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
> 
> They list tools for Python, Perl, PHP and JavaScript, proving that
> dynamic languages can be safe too. These tools go much farther than a
> type system by following the data flow in and out of functions.
> 
> http://stackoverflow.com/questions/141498/what-open-source-c-static-analysis-tools-are-available
> 
> It looks like the OSS splint program would find that infinite loop -
> see the example here:
> http://en.wikipedia.org/wiki/Splint_%28programming_tool%29

splint certainly provides useful output. I changed my code around so
that the boundary condition would be -1 and use greater than. As splint
warns, 0 could be confusing.

I rant splint on both. In the case of the boundary condition -1 
(Version 2), it warns that I am using two different types in my 
compare. Very nice. 

brian


// Version 1. Compare to zero
#include <stdio.h>

int main() {
  int a[] = {5,6,8,3,4};
  unsigned int i;


  // Compares to 0 
  for (i= (sizeof(a) -1)/sizeof(int) ; i >= 0; i--) {
    printf("%d\n",a[i]);
  }

  return 0;
}

brian at lamaquina:~/school/Project/practice$ splint test_loop.c
Splint 3.1.2 --- 03 May 2009

test_loop.c: (in function main)
test_loop.c:8:8: Assignment of arbitrary unsigned integral type to unsigned
                    int: i = (sizeof((a)) - 1) / sizeof(int)
  To ignore type qualifiers in type comparisons use +ignorequals.
test_loop.c:8:40: Comparison of unsigned value involving zero: i >= 0
  An unsigned value is used in a comparison with zero in a way that is either a
  bug or confusing. (Use -unsignedcompare to inhibit warning)

Finished checking --- 2 code warnings



// Version 2
#include <stdio.h>

int main() {
  int a[] = {5,6,8,3,4};
  unsigned int i;


  // Version 2. Compare to -1 
  for (i= (sizeof(a) -1)/sizeof(int) ; i > -1; i--) {
    printf("%d\n",a[i]);
  }

  return 0;
}

brian at lamaquina:~/school/Project/practice$ splint test_loop.c
Splint 3.1.2 --- 03 May 2009

test_loop.c: (in function main)
test_loop.c:8:8: Assignment of arbitrary unsigned integral type to unsigned
                    int: i = (sizeof((a)) - 1) / sizeof(int)
  To ignore type qualifiers in type comparisons use +ignorequals.
test_loop.c:8:40: Operands of > have incompatible types (unsigned int, int):
                     i > -1
  To ignore signs in type comparisons use +ignoresigns

Finished checking --- 2 code warnings

-- 
Brian Lavender
http://www.brie.com/brian/

"For every complex problem there is an answer that is clear, simple, and wrong."
- H. L. Mencken 


More information about the vox-tech mailing list