5

I have posted screenshot of my error code. enter image description here

heights output

enter image description here

please any one can help me?

Romit M.
  • 898
  • 11
  • 28

2 Answers2

3

I think the static analyzer is not seeing how _numberOfColumns can become non-zero, and hence its insistence that garbage is being assigned. You need to check that you are actually providing some means for _numberOfColumns to become non-zero.

Generally when I am writing loops that want to find the largest or the smallest value, I initialize the size variable to the largest (if I want the smallest) or smallest (if I want the largest) amount, and I think this will solve most of your issues:

float shortestHeight = FLT_MAX;
for (unsigned i = 0; i < _numberOfColumns; i++)
{
    // etc.
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

The analyzer is correct. Your code will access garbage memory if _numberOfColumns is 0, thus allocating 0 bytes for heights, making heights[0] garbage. The analyzer doesn't know what values _numberOfColumns can have, but you can tell it by using assert(_numberOfColumns>0).

Take this C program for example:

int main(int argc, const char * argv[])
{
    int n = argc-1;
    int *a = malloc(n*sizeof(int));
    for (int i=0; i<n; i++) {
        a[i] = i;
    }
    int foo = a[0];
    free(a);
    return foo;
}

the size of a is determined by the number of arguments. If you have no arguments n == 0. If you are sure that your program (or just that part of your program) will always assign something greater than 0 to a, you can use an assertion. Adding assert(n>0) will tell the analyzer exactly that.

Sebastian
  • 7,670
  • 5
  • 38
  • 50