Home > Blockchain >  What will happen if 0 is passed to %s in printf()?
What will happen if 0 is passed to %s in printf()?

Time:06-27

I understand that passing a null pointer will trigger an undefined behavior, but if I use calloc() to initialize a char array and print it, for example:

char * a = calloc(10, sizeof(char));
printf("%s\n", a);

calloc() should initialized the char array to 0. Since in ASCII table 0 refers to NULL, I expected undefined behavior. However, every time I run it, it will actually print nothing. Is this output fixed? Can I reason about the output?

CodePudding user response:

In C a string is generally understood to terminate at the first 0 byte encountered. Since the first byte in the result of calloc has value 0, it is interpreted as immediately ending the string, leaving you with the empty string.

  • Related