...
None-Compliant Code Example
This is a none-compliant code example showing that modification of the string value returned by the function getenv() will affect other processes that are using the same environmental variable at this given time.
| Code Block | ||
|---|---|---|
| ||
int foo()
{
char *env;
env = getenv("TEST_ENV");
env[0] = 'a';
/*Do some more things*/
return 0;
}
|
Compliant Code Solution
This is a compliant code solution. The code shows that if the programmer feel it is necessary to modify the value the string returned by the function getenv(), then the programmer should make a local copy of that string value, and then modify the local copy of that string.
| Code Block | ||
|---|---|---|
| ||
int foo()
{
char *env;
char *copy_of_env;
env = getenv("TEST_ENV");
copy_of_env = malloc( (strlen(env)+1) * sizeof(char) );
/* Error handling */
strncpystrcpy(copy_of_env, env, strlen(env));
copy_of_env[0] = 'a';
/*Do some more things*/
return 0;
}
|
...