Preventing Buffer Overruns in C++ 
by Richard Grimes


Example 1:

void __cdecl PrintHello(char* name)
{
   char buf[10];
   strcpy(buf, "hello ");
   strcat(buf, name);
   puts(buf);
}

Example 2:
(a)

#include <stdio.h>
#include <string.h>
#include <strsafe.h>

void main()
{
   char str[10];
   strcpy(str, "hello");
   puts(str);
}

(b)

error C2065: 'strcpy_instead_use_StringCbCopyA_or_StringCchCopyA' : undeclared identifier

(c)

#undef strcpy
#define strcpy strcpy_instead_use_StringCbCopyA_or_StringCchCopyA; 

Example 3:

char str[10];
HRESULT hr;
hr = StringCbCopy(str, sizeof(str), "hello");
if (SUCCEEDED(hr)) puts(str);

Example 4:

STDAPI StringCbCopyEx(
   TCHAR pszDest, size_t cbDest,
   LPCTSTR pszSrc, LPTSTR* ppszDestEnd,
   size_t* pcbRemaining, DWORD dwFlags);






1


