Lines without a '\ 0' char?

If by mistake I define a char array without "\ 0" as its last character, what happens then? I ask this because I noticed that if I try to iterate over the while (cnt! = '\ 0') array, where cnt is the int variable used as the index for the array and at the same time print the cnt values ​​to monitor what happens , the iteration stops at the last character + 2. Additional characters are, of course, random, but I can’t understand why it should stop after 2. When does the compiler automatically insert the character '\ 0'? Links to related documentation will be appreciated.

To clarify, I will give an example. Say the array "str" ​​contains the word doh (without "\ 0"). Printing the cnt variable in each loop would give me this DOH + or doh ^ etc.

+5
source share
6 answers

EDIT (undefined behavior)

Access to array elements outside the bounds of the array is undefined behavior.
Calling string functions with anything other than string C is undefined behavior.
Do not do that!

Line C is a sequence of bytes ending with a '\0'(a NUL terminator). All bytes must belong to the same object.


In any case, you see a coincidence!

But it can happen like this:

                        ,------------------ garbage
                        | ,---------------- str[cnt] (when cnt == 4, no bounds-checking)
memory ----> [...|d|o|h|*|0|0|0|4|...]
                  |   |   \_____/  -------- cnt (big-endian, properly 4-byte aligned)
                  \___/  ------------------ str
+5

char \0 ( " " ), , , . :

char strings[] = {'h', 'e', 'l', 'l', 'o'};

. , "+2", ; +50 , , \0 .

:

char strings[] = "hello";

. , C, , .

C , -. , , . , strncat(), , .

, , , , , , ( ).

+4

, *(str + 5) 0 ( , ASCII)

+3

, '\0'. - -, :

  • , '\0', . , : , , . , , , , , . , printf(), .

  • , , (, " " Linux).

  • , .

, C , , , , . , C , .

+3

C string . , , , " " \0 "char". -, .

, , , . , , undefined. . , "" - . . , , undefined, .

+3

, int int , 0.

0

All Articles