c - Which string manipulation functions should I use? -
on windows/visual c environment there's wide number of alternatives doing same basic string manipulation tasks.
for example, doing string copy use:
strcpy
, ansi c standard library function (crt)lstrcpy
, version included in kernel32.dllstrcpy
, shell lightweight utility librarystringcchcopy
/stringcbcopy
, "safe string" librarystrcpy_s
, security enhanced version of crt
while understand these alternatives have historical reason, can choose consistent set of functions new code? , one? or should choose appropriate function case case?
first of all, let's review pros , cons of each function set:
ansi c standard library function (crt)
functions strcpy
1 , choice if developing portable c code. in windows-only project, may wise thing have separation of portable vs. os-dependent code.
these functions have assembly level optimization , therefore fast.
there drawbacks:
- they have many limitations , therefore still have call functions other libraries or provide own versions
- there archaisms infamous
strncpy
kernel32 string functions
functions lstrcpy
exported kernel32 , should used when trying avoid dependency crt. might want 2 reasons:
- avoiding crt payload ultra lightweight executable (unusual these days not 10 years ago!)
- avoiding initialization issues (if launch thread
createthread
instead of_beginthread
).
moreover, kernel32 function could more optimized crt version: when executable run on windows 9 optimized core i13, kernel32 could use assembly-optimized version.
shell lightweight utility functions
here valid same considerations made kernel32 functions, added value of more complex functions. doubt actively maintained , skip them.
strsafe function
the stringcchcopy
/stringcbcopy
functions personal choice: designed, powerful, , surprisingly fast (i remember whitepaper compared performance of these functions crt equivalents).
security-enhanced crt functions
these functions have undoubted benefit of being similar ansi c equivalents, porting legacy code piece of cake. template-based version (of course, available when compiling c++). hope standardized. unfortunately have number of drawbacks:
- although proposed standard, have been rejected non-windows community (probably because came microsoft)
- when fail, don't return error code execute invalid parameter handler
conclusions
while personal favorite windows development strsafe library, advice use ansi c functions whenever possible, portable-code thing.
in real life, developed personalized portable library, prototypes similar security-enhanced crt functions (included powerful template based technique), relies on strsafe library on windows , on ansi c functions on other platforms.
Comments
Post a Comment