First, it is important to say that you can safely use this function. Her problem is that the programmer may forget or not know how to do this.
The first problem with 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 string copy is placed and then the operation is performed. If what is passed to this function is larger than the placeholder, it will place data beyond the placeholder. And this is one way to inject malicious code into an application you want to compromise.
Another problem is that it does not guarantee that the destination will be terminated by a% null value, which is what determines the end of a string , so another part of the code can read this memory waiting for this character to know when to stop reading and you will not find it. This problem also exists in 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 does not put an appropriate value (probably equal to what was allocated) it will also be insecure. It guarantees that it will have a null ending string appropriately.
If you do not have a C11 compiler, you can use strlcpy()
, if available, or strncpy()
, which still has problems, but is already a little better. Anyway, the programmer can always check before using the function if the source size is suitable for the target and can ensure that the null is placed at the end. Every decent C programmer has a function of his own 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"