Internationalization and localization tools


Locale-Sensitive Length Function

char *strndup(const char *s, size_t size);

Internationalization (I18n) Function Overview

This function is similar to strdup but always copies at most size bytes into the newly allocated string.

If the length of s is more than size, then strndup copies just the first size bytes and adds a closing null terminator. Otherwise all bytes are copied and the string is terminated.

This function is different to strncpy in that it always terminates the destination string.

I18n Issues

Note that while the documentation says strndup copies size characters it actually copies size bytes. This makes this function locale-sensitive in UTF-8 multibyte environments. For example, consider the simple case of a string which consists of a single multibyte character which contains 2 bytes. If stpncpy is used with a parameter of 1, only half of the multibyte character will be copied, resulting in an ill-formed string.

Additionally, there is no ANSI wide character version of this function.

These two issues combined mean that there is no suitable substitution for strndup that is readily available that supports either multibyte or wide character strings.

Note that since this function is simply a malloc followed by a strncpy, you may consider doing the malloc yourself and then calling strncpy. Also note that strncpy has its own issues however, and the documentation should be consulted.

Recommended Replacements*

*If you're already using the recommended function, see I18n Issues for other reasons why Globalyzer is detecting the function.

Locale-Sensitive Length Functions

 

Lingoport internationalization and localization services and software