Click here to Skip to main content
12,693,891 members (31,358 online)
Click here to Skip to main content

Stats

36.4K views
826 downloads
46 bookmarked
Posted

Secure String Handling in Windows Applications

, 9 Mar 2014 CPOL
This article explains about Strsafe, Secured C run time library (CRT) and safe STL functions.
// StringCopy.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <atlstr.h>
#define MAX_CHAR 255
#define BUFSIZE 85
#include <strsafe.h>

int _tmain(int argc, _TCHAR* argv[])
{

  /* declare unsafe copy variable */
  wchar_t unsafe_copy_str1[]=L"Hello world";
  wchar_t unsafe_copy_str2[MAX_CHAR];

  /* demo unsafe wcscpy without buffer check */
  wprintf(L"#### String Copy demo using wcscpy #### \n");
  wcscpy (unsafe_copy_str2, unsafe_copy_str1);
  wprintf (L"After copy string = %s\n\n", unsafe_copy_str2);
   
 	
  /* declare safe CRT variable */
  wchar_t safe_copy_str1[]=L"Hello world";
  wchar_t safe_copy_str2[MAX_CHAR];

  /* demo safe CRT variable */
  wprintf(L"#### String Copy demo using wcscpy_s #### \n");
  wcscpy_s( safe_copy_str2, _countof(safe_copy_str1),safe_copy_str1 );
  wprintf (L"After copy string = %s\n\n", safe_copy_str2);


  /* declare strsafe variable */
  wchar_t safe_copy_str3[]=L"Hello world";
  wchar_t safe_copy_str4[MAX_CHAR];

  /* demo strsafe variable */
   wprintf(L"#### String Copy demo using StringCchCopy #### \n");
    HRESULT Res;
    Res=StringCchCopy(STRSAFE_LPWSTR(safe_copy_str4), sizeof(safe_copy_str4), STRSAFE_LPWSTR(safe_copy_str3));
    if (Res != S_OK) {
      wprintf(L"StringCbCopy Failed: %s\n", safe_copy_str4);
      exit(-1);
   }

	wprintf (L"After copy string = %s\n\n", safe_copy_str4);


	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

R.selvam
Software Developer (Senior)
India India
Selvam has worked on several technologies like Core Java, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoy writing them too. He has been awarded as a Microsoft Community Star in 2004, MVP in 2005-06, SCJP 5.0 in 2009, Microsoft Community Contributor(MCC) 2011.

Github : https://github.com/selvamselvam
Web site: http://www.careerdrill.com

You may also be interested in...

Pro
Pro
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170118.1 | Last Updated 9 Mar 2014
Article Copyright 2011 by R.selvam
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid