This is the third program in C language. This program is to demonstrate string concept.
From study I know that string at its end has a null character '\0' to terminate the string.
I wrote that code :
main()
{
char name[8];
strcpy(name, "Mahmoud");
printf("The contents of name are %s\n", name);
getchar();
}
In this code I declare array of type char to save string in it. My name "Mahmoud" is 7 chars and I declare name with size 8 which is 7 for "Mahmoud" and 1 for '\0', and it works correctly.
But in the following code:
main()
{
char name[8];
strcpy(name, "MahmoudEmam");
printf("The contents of name are %s\n", name);
getchar();
}
When I display name the output is "MahmoudEmam", although the size of name is 8.
How does it do ?
C does not perform any array bounds checking (maybe with C11...). You are writing past the end of your array : it is an undefined behavior (anything can happen).
The fact you see the full name displayed is undefined behavior. Basically, you are copying more than 7 characters and a terminating 0 (total of 8 characters) into storage reserved only for 7 characters and a terminating 0.
It just happens to work, but could as easily cause your program to crash.
This is why C is considered a lower level programming language, or, as the phrase used to go many years ago, a high level assembly programming language.
You the programmer have to check the length of the copy operation's target, using a construct like sizeof(name), and make sure what you are copying does not override that space. You must also keep in mind for
string termination, enough space + 1 to account for the terminating '\0'.
Don't forget that using sizeof with a string allocated with malloc will return a value of 4 for a 32-bit pointer, or the pointer length of your hardware. In that case, you'll have to rely on strlen to get the buffer length, or store what size was used to malloc the string.
Finally, when passing a string pointer to a function, writing the function to have a buffer length is very helpful. You cannot get the true buffer length. strlen only returns the string length, not the buffer size actually pointed to by the pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With