Safe String Functions In Mac OS X and Linux Safe String Functions In Mac OS X and Linux windows windows

Safe String Functions In Mac OS X and Linux


There are two strategies for safe string manipulation. The Linux / glibc maintainers refuse to add safe functions, arguing that you should keep the length of your strings at hand and use memcpy.

On the other hand, Mac OSX includes strlcpy and strlcat from BSD. snprintf and asprintf can be used on both platforms to much the same effect:

size_t strlcpy(char *d, char const *s, size_t n){    return snprintf(d, n, "%s", s);}size_t strlcat(char *d, char const *s, size_t n){    return snprintf(d, n, "%s%s", d, s);}

You could also consider using the BSD implementation found here. If your code will be compiled on multiple platforms, you can test for the presence of glibc using pre-defined library macros:

#if defined __GNU_LIBRARY__ || defined __GLIBC__    size_t strlcpy(char *, char const *, size_t);    size_t strlcat(char *, char const *, size_t);#endif 

Conversion between character encodings is most easily handled using the iconv interface.


OSX has strlcpy and strlcat. Linux doesn't currently have them, to my knowledge, but it's easy enough to bring those functions in from, say, OpenBSD.


You can use gcc's -D_FORTIFY_SOURCE=2 option, for Linux you can go more advanced, for that you should read Secure Programming with gcc & glibc .