There is no way for the strcpy
function to know the size of the destination buffer. This is why strcpy
is somewhat deprecated: you can't tell, from looking at a call of the function, whether it's been used correctly or not.
If the destination buffer is not large enough, strcpy
has undefined behavior: the rules of the language say that anything can happen. In practice, it'll overwrite some memory: a buffer overflow. It's up to the programmer to ensure that they only ever use strcpy
safely. It's the programmer's responsibility, not the function implementer's responsibility, and in practice the implementer can't do anything about it: the size of the destination buffer is not available to check.
The destination buffer for strcpy
doesn't need to contain a valid string. This is a perfectly valid use of strcpy
:
char dst[10] = "car";
char src[12] = "green";
strcpy(dst, src);
The destination buffer is 10 bytes long, which is enough for a string of up to 9 characters (plus one for the terminating null byte). It happens to contain a shorter string at that moment, but that doesn't matter. Before the copy, dst
is a 10-byte array containing something like
'c', 'a', 'r', 0, 'J', 'U', 'N', 'K', '.', '.'
(what's after the 0 byte can be anything, this is just an example). After the copy, dst
contains
'g', 'r', 'e', 'e', 'n', 0, 'N', 'K', '.', '.'
To put it another way: strcpy
doesn't exactly copy a string to a string. It copies a string to a buffer. After the copy, that buffer contains a string. What matters is that the destination buffer is large enough to accommodate the string.
strcpy
writes to an existing buffer, it doesn't need to and shouldn't call malloc
. There's a different function, strdup
, which copies a string and allocates just enough memory for it; this function doesn't take the destination buffer as an argument (how could it: it creates the destination buffer).