Quick strlen question
y
is not null-terminated. strlen()
counts characters until it hits a null character. Yours happened to find one after 6, but it could be any number. Try this:
char y[] = {'t','e','s','t', '\0'};
Here's what an implementation of strlen()
might look like (off the top of my head -- don't have my K&R book handy, but I believe there's an implementation given there):
size_t strlen(const char* s)
{
size_t result = 0;
while (*s++) ++result;
return result;
}
This
char y[4] = {'t','e','s','t'};
is not a proper zero-terminated string. It's an array of four characters, without the terminating '\0'
. strlen()
simply counts the characters until it hits a zero. With y
it simply counts over the end of the array until it accidentally finds a zero byte.
Doing this you are invoking undefined behavior. The code might just as well format your hard drive.
You can avoid this by using the special syntax for character array initialization:
char y[] = "test";
This initializes y
with five characters, since it automatically appends a '\0'
.
Note that I also left the array's size unspecified. The compiler figures this out itself, and it automatically re-figures if I change the string's length.
BTW, here's a simple strlen()
implementation:
size_t strlen(const char* p)
{
size_t result = 0;
while(*p++) ++result;
return result;
}
Modern implementations will likely not fetch individual bytes or even use CPU intrinsics, but this is the basic algorithm.
The following is not a null terminated array of characters:
char y[4] = {'t','e','s','t'};
Part of strlen()
's contract is that it be provided with a pointer to a null terminated string. Since that doesn't happen with strlen(y)
, you get undefined behavior. In your particular case, you get 6
returned, but anything could happen, including a program crash.
From C99's 7.1.1 "Definition of terms":
A string is a contiguous sequence of characters terminated by and including the first null character.