Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one always cast printf parameters?

Tags:

c

c99

A while ago I was hunting for bug a that was causing wrong numeric data being written to log files. Turned out that the problem was that code equivalent to the following:

int main(void) {
    struct {
        double a;
        int b;
    } s = { 1, 2 };

    printf("%lf\n", s.a);
    printf("%lf\n", s.b);
}

was outputting

1.000000
1.000000

Apparently printf was expecting the second value in floating point registers, not in the stack. To prevent such mistakes from happening in the future, should one cast all printf parameters to be sure that they really are of the expected type?

like image 759
andyn Avatar asked Dec 26 '22 21:12

andyn


1 Answers

According to C99 standard. Mismatch in format specifier and datatype of actual data to be printed is Undefined behavior

Here b is and int so if you give "%d" in second printf() function. It will print the correct value otherwise Behavior is Undefined

From c99

7.19.6 9 If a conversion specification is invalid, the behavior is undefined.242) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined

like image 104
Omkant Avatar answered Dec 28 '22 11:12

Omkant