...
Altering the string returned by setlocale()
or the structure returned by localeconv()
results in undefined behavior. Furthermore, C99 imposes no requirements on the contents of the string by setlocale()
. Consequently, a program should make no assumptions as to the string's internal contents or structure.
Wiki Markup |
---|
Finally, C99 Section 7.21.6.2 \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] states: |
...
Code Block | ||
---|---|---|
| ||
const char *env;
char *copy_of_env;
env = getenv("TEST_ENV");
if (env == NULL) {
/* Handle error */
}
copy_of_env = strdup(env);
if (copy_of_env == NULL) {
/* Handle error */
}
trstr(copy_of_env,'\"', '_');
if (setenv("TEST_ENV", copy_of_env, 1) != 0) {
/* Handle error */
}
|
Noncompliant Code Example (setlocale()
)
This noncompliant code example modifies the string returned by setlocale()
by terminating the string when '.' is encountered such as âen_US.iso88591â to âen_USâ. In this case, the behavior is undefined.
Code Block | ||
---|---|---|
| ||
void terminate_on_dot(char *str){ int i; for (i = 0; i < strlen(locale); i++){ if(locale[i] == '.'){ locale[i] = â\0â; break; } } } /* ... */ char *locale = setlocale(LC_ALL, ""); if (locale == NULL) { /* Handle error */ } terminate_on_dot(locale); /* ... */ |
Compliant Solution (setlocale()
)
Similar to the case of getenv()
, this compliant solution makes a local copy of that string value and then modifies the local copy.
Code Block | ||
---|---|---|
| ||
const char *locale;
char *copy_of_locale;
locale = setlocale(LC_ALL, "");
if (locale == NULL) {
/* Handle error */
}
copy_of_locale = (char *)malloc(strlen(locale) + 1);
if (copy_of_locale == NULL) {
/* Handle error */
}
strcpy(copy_of_locale, locale);
terminate_on_dot(copy_of_locale);
/* ... */
|
Risk Assessment
Depending on the implementation, modifying the object pointed to by the return value of these functions causes undefined behavior. Even if the modification succeeds, the modified object may be overwritten by a subsequent call to the getenv()
, setlocale()
, localeconv()
, or strerror()
functions.
...