strcpy_s / wcscpy_s – DONT DO IT!

The good old strcpy never checked the destination buffer size. And today that is considered a Bad Thing – and I think I agree. Indeed, later versions of Visual Studio will refuse to compile this (and related) functions unless you add a predefinedĀ _CRT_SECURE_NO_WARNINGS.

So, in theory, the introduction of strcpy_s which DOES check buffer size is a Good Thing. Or so you would think. But what happens if the destination buffer _is_ too small ? Well, if you read the MSDN documentation it kinda suggests the function returns a nice helpful error code. Wrong ! Your application blows up and is terminated, not even a try-catch block will help you.

Seriously Microsoft, just whose stupid idea was it to implement things this way ? Do hope you’ve sacked ‘em / sent them to work for Apple.

But all is not lost. Instead, useĀ strncpy_s as follows:

strncpy_s( pDestination, destinationSize, pSource, _TRUNCATE );

I bet there are infinitely more programs out there blowing up because of strcpy_s than there are hackers causing buffer overruns.

Leave a Reply