Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function works OK, but returns garbage

I have this function:

float calc_nnc(struct ImageWindow *window1, struct ImageWindow *window2) {
    /* More code */
    double numerator = (double) sum_a_x_b;
    double divisor = ( sqrt(sum_a) * sqrt(sum_b) );
    double result = numerator / divisor;
    float resultf = (float) result;

    printf("numerator: %lf, divisor: %lf, result: %lf, resultf: %f\n",
        numerator, divisor, result, resultf);

    return resultf;
}

The printf prints the results I expect to see:

a x b = 1383, a = 1776, b = 4959
numerator: 1383.000000, divisor: 2967.690011, result: 0.466019, resultf: 0.466019

However, when I try to print the result of calc_nnc in another function:

float nnc_likeness;
unsigned int x, y;

for (y = 0; y <= y_max; y++) {
    for (x = 0; x <= x_max; x++) {
        set_image_window(&window_big, big, x, y, width, height);
        nnc_likeness = calc_nnc(&window_small, &window_big);
        printf("likeness: %f\n", nnc_likeness);
    }
}

I get garbage:

likeness: 1055824384.000000

That is, I see the correct values calc_nnc is computing, but right after that I see a corrupted value for nnc_likeness.

Any idea what's happening? Thanks!

like image 437
Albus Dumbledore Avatar asked Jun 03 '11 18:06

Albus Dumbledore


1 Answers

You probably have no prototype for calc_nnc in the context where you call it, so your compiler thinks its return type is int (as per the spec). A quick test program:

#include <stdio.h>

union u {
  float f;
  int   i;
};

int main(int argc, char **argv)
{
  union u a;
  union u b;

  a.f = 0.466019;
  b.i = 1055824384;

  printf("%d %f\n", a.i, a.f);
  printf("%d %f\n", b.i, b.f);

  return 0;
}

Gives this output:

1055824395 0.466019
1055824384 0.466019

Include a correct prototype that tells your code that calc_nnc returns float and you'll be all set. Turning more warnings on will catch this problem, too.

like image 169
Carl Norum Avatar answered Nov 02 '22 03:11

Carl Norum