Mr.Curious
Mr.Curious

Reputation: 292

Why to use _tcscpy_s instead of _tcscpy?

I am new to C++ programming. I am carrying out an 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 the warning go away:

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

What is the actual difference between _tcscpy and _tcscpy_s, and how does it make the code safe?

Upvotes: 0

Views: 4430

Answers (1)

Alex Guteniev
Alex Guteniev

Reputation: 13689

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.

Upvotes: 6

Related Questions