I am trying to understand the difference/disadvantages of strcpy and strncpy. Can somebody please help:
void main()
{
char src[] = "this is a long string";
char dest[5];
strcpy(dest,src) ;
printf("%s \n", dest);
printf("%s \n", src);
}
The output is:
this is a long string
a long string
QUESTION: I dont understand, how the source sting got modified. As per explanation, strcpy should keep copying till it encounters a '\0', so it does, but how come "src' string got modified.
Please explain.
The strcpy() function copies string2, including the ending null character, to the location that is specified by string1. The strcpy() function operates on null-ended strings. The string arguments to the function should contain a null character (\0) that marks the end of the string.
Problem with strcpy(): The strcpy() function does not specify the size of the destination array, so buffer overrun is often a risk. Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk.
Both strcpy() and strcat() functions can accidentally overwrite memory locations reserved for other variables or program areas if sufficient size is not allocated in advance. Modern programmers are thus advised to use function related to string class and get rid of such problems.
In computer programming, the strlcpy function is intended to replace the function strcpy (which copies a string to a destination buffer) with a secure version that cannot overflow the destination buffer.
The easy answer is that you have (with that strcpy() call) done something outside the specifications of the system, and thus deservedly suffer from undefined behaviour.
The more difficult answer involves examining the concrete memory layout on your system, and how strcpy() works internally. It probably goes something like this:
N+28 "g0PP"
N+24 "trin"
N+20 "ng s"
N+16 "a lo"
N+12 " is "
src N+08 "this"
N+04 "DPPP"
dest N+00 "DDDD"
The letters D
stand for bytes in dest, the letters P
are padding bytes, the 0
characters are ASCII NUL characters used as string terminators.
Now strcpy(dest,src) will change the memory content somewhat (presuming it correctly handles the overlapping memory areas):
N+28 "g0PP"
N+24 "trin"
N+20 "g0 s"
N+16 "trin"
N+12 "ng s"
src N+08 "a lo"
N+04 " is "
dest N+00 "this"
I.e. while dest now "contains" the full string "this is a long string" (if you count the overflowed memory), src now contains a completely different NUL-terminated string "a long string".
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