...
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 (localeconv()
)
In this noncompliant example, the object returned from the C Standard Library function localeconv()
is modified.
Code Block |
---|
|
void f2(void) {
struct lconv *conv = localeconv();
if ('\0' == conv->decimal_point[0]) {
conv->decimal_point = "."; /* violation */
}
if ('\0' == conv->thousands_sep[0]) {
conv->thousands_sep = ","; /* violation */
}
/* ... */
}
|
Compliant Solution (localeconv()
) (Local Copy)
This compliant solution makes a local copy of the object and then modifies it.
Code Block |
---|
|
void f2(void) {
struct lconv *conv = localeconv();
if (conv == NULL) {
/* Handle error */
}
copy_of_conv = (char *)malloc(sizeof(lconv) + 1);
if (copy_of_conv == NULL) {
/* Handle error */
}
memcpy(copy_of_conv, conv, sizeof(lconv));
if ('\0' == copy_of_conv->decimal_point[0]) {
copy_of_conv->decimal_point = ".";
}
if ('\0' == copy_of_conv->thousands_sep[0]) {
copy_of_conv->thousands_sep = ",";
}
/* ... */
} |
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 can be overwritten by a subsequent call to the getenv()
, setlocale()
, localeconv()
, or strerror()
functions.
...