Strings without a '\0' char?

后端 未结 6 537
醉梦人生
醉梦人生 2020-12-10 18:58

If by mistake,I define a char array with no \\0 as its last character, what happens then?

I\'m asking this because I noticed that if I try to iterate th

6条回答
  •  轮回少年
    2020-12-10 19:24

    As far as most string-handling functions are concerned, strings always stop at a '\0' character. If you miss this null-terminator somewhere, one of three things will usually happen:

    • Your program will continue reading past the end of the string until it finds a '\0' that just happened to be there. There are several ways for such a character to be there, but none of them is usually predictable beforehand: it could be part of another variable, part of the executable code or even part of a larger string that was previously stored in the same buffer. Of course by the time that happens, the program may have processed a significant amount of garbage. If you see lots of garbage produced by a printf(), an unterminated string is a common cause.

    • Your program will continue reading past the end of the string until it tries to read an address outside its address space, causing a memory error (e.g. the dreaded "Segmentation fault" in Linux systems).

    • Your program will run out of space when copying over the string and will, again, cause a memory error.

    And, no, the C compiler will not normally do anything but what you specify in your program - for example it won't terminate a string on its own. This is what makes C so powerful and also so hard to code for.

提交回复
热议问题