Home > Mobile >  how does printf know the end of a string when the null terminator is not part of the string?
how does printf know the end of a string when the null terminator is not part of the string?

Time:12-09

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

int main(void)
{
    char str[10] = "testonetwo";
    printf("str [%s]\n", str);
    return (0);
}

I tried printing that string str and expected undefined behaviour but it printf str normally.

CodePudding user response:

how does printf know the end of a string when the null terminator is not part of the string?

printf does not know where the array str ends. If the call printf("str [%s]\n", str) is implemented with an actual call to a printf implementation (rather than optimized by the compiler to some other code), then str is converted to a pointer to its first element, and only this pointer is passed to printf. printf then examines memory byte-by-byte. For the first ten bytes, it sees elements of str. Then it access memory outside of str. What happens then is usually one of:

  • There are additional non-null bytes in memory, and printf writes them too, until it finds a null character.
  • There is a null byte in memory immediately after str, and printf prints only the bytes in str.
  • The memory printf tries to access is not mapped, and a segment fault or other exception occurs.

If the compiler did optimize the call into other code, other behaviors may occur. The C standard does not impose any requirements on what may happen.

  • Related