...
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 */
}
strtr(copy_of_env,'\"', '_');
if (setenv("TEST_ENV", copy_of_env, 1) != 0) {
/* Handle error */
}
|
Noncompliant Code Example
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
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
The modified string may be overwritten by a subsequent call to the getenv()
function. Depending on the implementation, modifying the string returned by getenv()
may or may not modify the environment.
...