0

I'm using sprintf - sscanf combination to rounding floating decimals and did it this way

float rounding(float number)
{
    char* rounded_number;
    float rounded;
    sprintf(rounded_number, "%.2e", rounded_number);
    sscanf(rounded_number, "%e", &rounded);
    return rounded;
}

And I called it once outside a loop and once in a loop. Trying outside any loop gives expected results, but calling

for (int j = 1; j < 101; j++)
    printf("%f", rounding( 1.0 / ((float) j)));

gives a segmentation fault.

Can someone explain? Thanks.

1 Answers1

0

Your sprintf call has undefined behavior because the destination pointer is uninitialized, to sprintf tries to write to some random location in memory, most likely causing a segmentation fault.

Furthermore, you pass rounded_number instead of number as the argument for %.2e which is another case undefined behavior.

You should use snprintf and pass a local array:

float rounding(float number) {
    char buf[32];
    snprintf(buf, sizeof buf, "%.2e", number);
    sscanf(buf, "%e", &number);
    return number;
}

Note however that the rounded number will not represent the exact values with 2 decimals in many cases. Floating point types use a binary encoding that cannot accurately represent most decimal fractions: only whole multiples of 1, 0.5 and 0.25 are accurately represented.

chqrlie
  • 131,814
  • 10
  • 121
  • 189