First it is important to say that it is possible to use this function safely. Her problem is that the programmer may forget or not know how to do this.
The first problem of the function is that it does not consider the size of what it is copying, so it is possible to overwrite an area of memory that was not intended. Usually the memory is allocated where the copy of the string will be placed and then the operation is done. If what is passed to this function is larger than the reserved space, it will put data beyond the reserved space. And this is one of the ways to inject malicious code into an application that wants to commit.
Another problem is that it does not guarantee that the destination will be terminated by a null value \0
, which is what determines the end of a string, then another part of the code can read this memory waiting for this character to know when to stop reading and will not find. This problem also exists in the strncpy()
.
The function strcpy_s()
(only available in C11) requires you to pass the size of what will be copied and the function will respect this. Of course, if the programmer doesn’t put a proper value (probably equal to the one allocated) it will also be insecure. It ensures that at the end has a null ending to string adequately.
If you don’t have a C11 compiler, you can use strlcpy()
, if available, or strncpy()
, that still has problems, but is already a little better. Anyway the programmer can always check before using the function if the size of the source is suitable for target and can ensure that the null is placed at the end. Every decent C programmer has a proper function to do this for him if the compiler he uses does not provide a standard function.
char * txt = malloc(10);
strcpy(txt, "teste maior do que devia"); //aqui já era! Vai ocupar uma memória indevida
strcpy_s(txt, 10, "teste maior do que devia"); //aqui só vai usar "teste mai"
I put in the Github for future reference.
The last line would be
strcpy_s
? Results in build error:too many arguments to function ‘strcpy’
– eightShirt
Oops, corrected by.
– Maniero
In practice, I couldn’t get this code to work, but I did:http://en.cppreference.com/w/string/byte/strcpy. However, I tried to change the size at
strcpy_s
and made no difference. I couldn’t visualize thestrcpy_s
being insecure. You can exemplify this?– eightShirt
But she’s not insecure.
– Maniero
But you said in the answer, "of course if the programmer doesn’t put a proper value (probably equal to what was allocated) it will also be insecure." But I could not test this situation. In fact, I tried testing with
2 * tamanho
and she tooktamanho
.– eightShirt
I don’t know you tested it, so I can’t talk about it.
– Maniero
Okay, but you can quote an example of code where
strcpy_s
is insecure? This statement - thatstrcpy_s
can be insecure - is in your answer.– eightShirt
I don’t have a compiler to test. Anything can be unsafe if using wrong.
– Maniero