1

I wrote a simple dot product function on an MBED LPC1768:

float dotProduct(float a[], float b[], int length){
    float sum;
    int i;
    for (i = 0; i < length; i++){
        sum = sum + a[i]*b[i];
    }
    return sum;
}

I have two calls to dotProduct in a row in my program that (for testing) dot two 128 element 1-vectors ({1,1,1...1}) and print them to serial. So the expected result should just be 128 and 128. The variable sum seems to persist, however, because I get 128 and 256. Furthermore, if I change the float sum declaration to float sum = 0, I get the desired result of 128 and 128. The variable sum is not static, so why does it persist between function calls? Thanks

Kevin Chan
  • 85
  • 1
  • 6

2 Answers2

3

The problem with "persistence" is that sum is used uninitialized, hence causing undefined behavior. In your case, however, sum gets allocated in the same place in memory where it has been during the prior invocation, thus creating an illusion of "persistence".

Note that your compiler has probably issued a warning to you, which you should not have ignored.

Fix this problem by adding initialization to your variables before using them:

float sum = 0;
for (int i = 0; i < length; i++){
    sum = sum + a[i]*b[i];
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You have UB as you read from an uninitialized variable and it pretty much useless to discuss what particular side effects of undefined behavior you have.

Slava
  • 43,454
  • 1
  • 47
  • 90