Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings without a '\0' char?

Tags:

c

string

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 through the array with while(cnt!='\0'), where cnt is an int variable used as an index to the array, and simultaneously print the cnt values to monitor what's happening the iteration stops at the last character +2.The extra characters are of course random but I can't get it why it has to stop after 2.Does the compiler automatically inserts a \0 character? Links to relevant documentation would be appreciated.

To make it clear I give an example. Let's say that the array str contains the word doh(with no '\0'). Printing the cnt variable at every loop would give me this: doh+ or doh^ and so on.

like image 751
kaiseroskilo Avatar asked Mar 13 '11 16:03

kaiseroskilo


1 Answers

EDIT (undefined behaviour)

Accessing array elements outside of the array boundaries is undefined behaviour.
Calling string functions with anything other than a C string is undefined behaviour.
Don't do it!

A C string is a sequence of bytes terminated by and including a '\0' (NUL terminator). All the bytes must belong to the same object.


Anyway, what you see is a coincidence!

But it might 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
like image 116
pmg Avatar answered Oct 17 '22 09:10

pmg