Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can printf() return differ from strlen()?

Tags:

c

string

Just out of curiosity:

#include <stdio.h>
#include <string.h>

enum { BIG_NUMBER = 1024 };

int main(void)
{
    char mysterious_string[BIG_NUMBER];

    if (scanf("%1023s", mysterious_string) == 1) {

        if (printf("%s", mysterious_string) != strlen(mysterious_string)) {
            // Can this state occur?
        }
    }
    return 0;
}

Can the inner 'if' return true? Can I blindly trust both of these functions (printf() and strlen()) to return the right value?

like image 811
Lucas Steffen Avatar asked Mar 23 '26 05:03

Lucas Steffen


1 Answers

It can absolutely be different.

If printf fails (for any number of reasons) then it will return a negative number which will not be the same as the value returned from strlen. In all other cases it will be the same.

Note: This is assuming the string is null terminated and that scanf works as expected.

like image 171
Fantastic Mr Fox Avatar answered Mar 25 '26 20:03

Fantastic Mr Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!