0

I got an interesting program and I would like to give an argument so that it will trigger the last else condition to execute the sh utility.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


#define answer 3.141593

void main(int argc, char **argv) {

    float a = (argc - 2)?: strtod(argv[1], 0);

    printf("You provided the number %f which is too ", a);

    if(a < answer)
                 puts("low");
    else if(a > answer)
                puts("high");
    else
                execl("/bin/sh", "sh", "-p", NULL);
}

One way I can do this is by giving NAN as the argument. However, I dont understand why giving 3.141593 as an argument does not convert to the same value as the "answer" variable.

Some one write a blogpost about it and the explanation is below: http://blog.pkt5.com/2012/09/iosmashthestack-level02alt.html

"This is because of the conversion by strtod which would convert 3.141593 that we enter to 3.14159298, a double. Hence it will always be too low"

Why would 3.141593 be converted to 3.14159298?

drdot
  • 3,215
  • 9
  • 46
  • 81
  • It doesn't: http://ideone.com/GrlEcS – Oliver Charlesworth Jun 19 '16 at 17:18
  • 1
    @OliverCharlesworth: the asker has it the strtod result being assigned to a float, unlike your ideone link. See http://ideone.com/D4Mw1i – AlexPogue Jun 19 '16 at 17:22
  • Data is stored using a finite number of bits with limited precision. Your question boils down to what numbers are representable using the number of bits in the data type. For example, according to [this IEEE standard](http://steve.hollasch.net/cgindex/coding/ieeefloat.html), single-precision floats are represented by 32 bits. Obviously these 32 "ones and zeros" can't represent all of the real numbers. The float can not precisely represent values greater than a certain precision. – AlexPogue Jun 19 '16 at 17:34

1 Answers1

0

The issue here is that float cannot represent all the values a double can represent. Consider this example:

double a = 3.141593;
float b = a;
double c = b;

is c equal to a? The answer is no, because there was a loss of precision in the intermediate step, where the value was truncated to fit into a float.

nemetroid
  • 2,100
  • 13
  • 20