sizeof strings

J

John Bode

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?

Not quite. You can store a string of *up to* 9 non-zero characters
followed by a '\0'. For example, you can store the string "one" in
name (name[10] = {'o', 'n', 'e', '\0', ?, ?, ?, ?, ?, ?}, where '?'
can be any value, including 0). The size of the buffer is 10, the
*maximum* length of a string you can store in that buffer is 9, and
the *actual* length of the string in the buffer is 3.
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?????

and why is it not complaining???

thank you
mohan gupta

C does not do bounds checking; if you try to write more data than a
buffer is sized to hold, that extra data will be written to the memory
immediately following the buffer. In this case, the '\0' is stored in
the byte immediately following name[9]. For example, if your buffer
is at location 0x8000 and sized to hold 10 characters, and you write
100 characters to it, the extra 90 characters will be stored starting
at address 0x800A. Depending on whether you were keeping anything
important at 0x800A, this could be a problem.
 
M

Mark L Pappin

John Bode said:
C does not do bounds checking;

C implementations are not _required_ to do bounds checking, but
likewise are not _prohibited_ from doing so.

mlp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,800
Messages
2,569,657
Members
45,417
Latest member
BonitaNile
Top