hello everyone ,
this one might seem wired but i dont know why iam confused with this
simple stuff
the problem is :
char name[10];
this defines a array of char with size 10 where 0-8 positions(count 9)
can be characters and name[9] should be '\0' .right?
Yes... and no.
All you have done with
char name[10];
is defined the variable "name" to reference an array of 10 character
elements. You may fill this array in any way you please, so long as you do
not try to store an element value that is outside of the value range
permitted by a char entity.
A /string/ is a specific type of character array, which contains zero or
more non-zero char elements, followed by a single char element of zero
(\0). A string with 10 non-zero characters (i.e. "0123456789") is contained
in a character array of 11 elements ( i. e.
{'0','1','2','3','4','5','6','7','8','9',0} ), with the final element being
the \0 character.
but when i strcpy() a string of 10 characters (strlen()=10) into
name ,it works fine
and shows name[9]=a valid character from the string .
so where did the '\0' character of name[9] gone?????
You overflowed your name[] array.
A string of 10 characters (that is, strlen() returns 10) is stored in a
character array of 11 elements. The first 10 elements contain the non-zero
characters, and the 11'th element contains the terminating \0
When you strcpy()ed the string, you copied the first 10 characters of the
string to elements name[0] to name[9]. Since that's all the space that you
allocated to the name[] array, the next character (the terminating \0)
didn't wind up in the name[] array, but was placed somewhere else. This is
bad - you've introduced a buffer overflow, and caused your program to
exhibit undefined behaviour (which could include successful completion, if
you are lucky).
and why is it not complaining???
Because, strcpy() is a function (albeit, a function implemented by the
standard library), and the size of an array defined outside of a function
is not implicitly determinable from within a function (that's how C works).
You, as the programmer, are expected to cope with that, and ensure that you
do not pass strcpy() invalid values.
--
Lew Pitcher
Master Codewright & JOAT-in-training | Registered Linux User #112576
http://pitcher.digitalfreehold.ca/ | GPG public key available by request
---------- Slackware - Because I know what I'm doing. ------