Search code examples
cprintfnull-string

printf returns 6 instead of 0 when assigning a null string


Why does printf function return 6 instead of 0 when assigning NULL as string to it, although its printing nothing?

int main(void)
{
    int x;
    x = printf("%s", NULL);
    printf ("\n%d", x);
}

output is:

(null)
6

Solution

  • why does printf function return 6 instead of 0 when assigning NULL as string to it

    Because it printed 6 chars. "(null)" is 6 chars.

    although its printing nothing?

    It is printing "(null)". That's 6 chars.

    Note that passing NULL as an argument to %s format specifier is invalid in the first place and causes undefined behavior. Some implementations, like the one you are using, are printing "(null)" instead of crashing.