Are there safe string copy function?

Started by
4 comments, last by MrEvil 18 years, 10 months ago
I find the strcpy strcat etc function is not safe,so I must wrtie safe function ? I know maybe stl string work.but in c no good string function?
Advertisement
Um... You mean like strncpy and strncat that take an extra parameter that specifies maximum count of bytes copied?

Or do you by "safe" mean something other?

Oxyd
No, C has no safe copy functions. For safety, use std::string.
Strncpy and strncat could be considered safe, but saying that their actual behaviour is unintuitive would be an understatement. C99 brings a few useful new functions too (such as snprintf, with proper termination).
Just be sure to study the documentation and you can use them in a safe way.

If you intend to use C-strings then I suggest writing your own set of wrapper functions for the most tedious tasks. At least that's should prove a good way to learn how to handle them.
std::string source("Hello");std::string copy = source;//copy a stringcopy+=", World!";//concatenate a stringcopy+=copy;


etc.
I'd advise using std::string if possible, but if that isn't possible (e.g., you are maintaining code that uses char* extensively), the new release (Whidbey) of Visual C++ contains a Secure CRT (C Runtime Library), which exports a few more string functions.

The new functions are designed to check output buffer sizes, etc., so that arrays are not overwritten. The new functions are strcpy_s, strcat_s, tmpnam_s, etc.

The new functions have been submitted to the standards committee for review, so they may appear in other compilers at a later stage.

Refer to this msdn blog for more info.

This topic is closed to new replies.

Advertisement