Menu

No Out Of Bounds error on inside for loop

2019-11-14
2019-11-16
  • Gabriel Anzziani

    No error reported on these two cases, which should report Out of Bound accesses to the array:

    Case 1: There is an unkown function that uses the index, however, the index is not being modified
    Case 2: The index is modified which causes accessing the array out of bounds

    void test(void) {
        int array[4]={1,2,3,4};
    // Case 1
        for (int i=1; i <= 4; i++) {
            function(i);
            array[i]=0; // no error!?
        }
    // Case 2
        for (int i=0; i < 4; i++) {
            i=i+10;
            array[i]=0; // no error
        }
        // errors below valid
        for (int i=1; i <= 4; i++) {
            array[i]=0;
        }
        printf("%d", array[4]);
    }
    
     
  • Daniel Marjamäki

    Thanks for this input. Very valuable. For case 1 Cppcheck really can't warn, because function might change i. If you show the function declaration Cppcheck does warn. You get a warning for this code:

    void function(int);
    
    void test(void) {
        int array[4]={1,2,3,4};
    // Case 1
        for (int i=1; i <= 4; i++) {
            function(i);
            array[i]=0; // no error!?
        }
    }
    

    For case 2.. I believe it's a genuine false negative. We should be able to catch this.

     
    • Gabriel Anzziani

      Thanks for the reply.
      For case 1, I was actually doing something like:

      #include <stdio.h>
      .
      .
              printf("%d",i);
      

      And I did not get the warning. Then I noticed it also happened with any unknown function that uses i. Since i is passed by value it is not being modified, cppcheck should notice this.

       

      Last edit: Gabriel Anzziani 2019-11-15
      • Daniel Marjamäki

        hmm.. if you use printf then we should be able to warn.

        Since i is passed by value it is not being modified, cppcheck should notice this.

        We really can't assume that.

        imagine:

        #define function(i)   i=0;
        
        void test(void)
        {
            int array[4]={1,2,3,4};
            for (int i=1; i <= 4; i++) {
                function(i);
                array[i]=0; // no error!?
            }
        }
        
         

        Last edit: Daniel Marjamäki 2019-11-16
        • Daniel Marjamäki

          If printf is used (or any other standard function that does not modify the value) we should warn. I created ticket https://trac.cppcheck.net/ticket/9478

           
  • Daniel Marjamäki

    I created this ticket for "case 2"
    https://trac.cppcheck.net/ticket/9475

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.