Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe String Functions In Mac OS X and Linux

Tags:

are there are equivalent secure string functions in Mac OSX and Linux just like the ones in Windows (strcpy_s,strncpy_s..etc) ?

What about functions that convert between multi-byte and wide characters?

like image 644
Orca Avatar asked Dec 31 '10 12:12

Orca


2 Answers

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.

like image 97
Fred Foo Avatar answered Sep 18 '22 23:09

Fred Foo


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.

like image 33
Chris Jester-Young Avatar answered Sep 17 '22 23:09

Chris Jester-Young