What happened when we do not include '\0' at the end of string in C?

后端 未结 5 2001
醉话见心
醉话见心 2020-12-10 23:09

In C, when I initialize my array this way:

char full_name[] = {
    \'t\', \'o\', \'a\', \'n\'
};

and print it with printf(\"%s\", fu

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 23:48

    Before passing the instruction pointer to a function expecting a c string you are implicitly entering a legally binding contract with that code block. In the primary section of this contract both parties agree to refrain from exchanging dedicated string length information and assert that all passed parameters declared as strings point to a sequence of characters terminated by \0 which gives each party the option to calculate the length.

    If you don't include a terminating \0 you will commit a fundamental breach of contract.

    The OS court will randomly sue your executable with madness or even death.

提交回复
热议问题