Home > Back-end >  Why to use _tcscpy_s instead of _tcscpy?
Why to use _tcscpy_s instead of _tcscpy?

Time:10-27

I am new to cpp programming and i am carrying out SAST violations check for my code and the scan throws a warning:

_tcscpy(destination_array,Source);

"The dangerous function, _tcscpy, was found in use at line 58 in Source.cpp file. Such functions may expose information and allow an attacker to get full control over the host machine"

So instead now i had to use this which makes warning go away:

_tcscpy_s(destination_array,_countof(destination_array),Source);

What is the actual difference between _tcscpy and _tcscpy_s and how it makes the code safe ?

CodePudding user response:

The actual difference is that _s functions check the destination buffer before writing to it. If the buffer is too small then either the program is aborted, or an error value is reported, depending on the current error handler.

This prevents buffer overrun attacks, when malicious data is formed in some specific way to overwrite other data and gain the control over the program.

Sure the prevention only works if the size of destination buffer is passed correctly. If not, buffer overruns and attacks are still possible.

Even if the application does not have security implication, it may be useful to use _s functions anyway to avoid hard to pinpoint memory corruption bugs.

Visual C provides a templated version of _tcscpy_s, so for arrays instead of

_tcscpy_s(destination_array,_countof(destination_array),Source);

you can use

_tcscpy_s(destination_array,Source);

this is even more safe, as the size is deduced, so an incorrect size is not possible.

  • Related