From Microsoft:
Here's some example C code using the current C runtime functions:
void UnsafeFunc(LPTSTR szPath,DWORD cchPath) { TCHAR szCWD[MAX_PATH];
GetCurrentDirectory(ARRAYSIZE(szCWD), szCWD); strncpy(szPath, szCWD, cchPath); strncat(szPath, TEXT("\\"), cchPath); strncat(szPath, TEXT("desktop.ini"),cchPath); }
The same code using strsafe is:
bool SaferFunc(LPTSTR szPath,DWORD cchPath) { TCHAR szCWD[MAX_PATH];
if (GetCurrentDirectory(ARRAYSIZE(szCWD), szCWD) && SUCCEEDED(StringCchCopy(szPath, cchPath, szCWD)) && SUCCEEDED(StringCchCat(szPath, cchPath, TEXT("\\"))) && SUCCEEDED(StringCchCat(szPath, cchPath, TEXT("desktop.ini")))) { return true; }
return false; }
Pop quiz - what does this code actually do?
Answer: GetCurrentDirectory() gets the CWD. The first strncpy() copies the CWD into szPath. The second one adds a backslash, and the third one adds 'desktop.ini'.
Oh - you mean:
def SafeByDefault(): import os return os.getcwd() + r'desktop.ini'
Right.
Or, if you really don't want to get too far away from C:
#include <string> using namespace std;
string SafeInCxx() { TCHAR szCWD[ MAX_PATH ]; GetCurrentDirectory( ARRAYSIZE(szCWD), szCWD ); return (string) szCWD + "\\desktop.ini"; }
Safe, and at the same time almost readable. Why do people still write applications in pure C? Even if you don't know C++, you can still use a C++ compiler and take advantage of things like the standard library's string-handling routines.
A lot of people out there will tell you that you have to either program totally in C or totally in C++, but that's not true. You can use a C++ compiler and use as much or as little of the language as you like. You'll find yourself writing more object oriented code over time, but you don't have to learn the whole language before you start. You don't have to put up with C's severe lack of useful datatypes!
Start by learning about std::string; it'll immediately make your code much more secure, and readable at the same time. Then take a look at std::list<> and see how you can throw out all the dodgy code you've written to manage linked lists and replace it with something that is at once simpler and more functional, and often faster.
Yes, the standard C++ library is quick. My informal tests have shown that iterating over a C++ vector using a typesafe iterator can actually be quicker than iterating over a C array using a pointer.
Your code will become larger, and will use more memory, but the memory usage will still only be 10% of what an equivalent app written in C# or Java would be -- the "bloat" here is a non-issue if you are writing code for a desktop machine.
12:53:19 AM
|