Wednesday, February 20, 2008

Awareness to env variable

Did not observe this issue so far, I was using an environment variable and the pointer to environment variable's value got modified in locally. And the next time when we call getenv to that same environment variable, It should give unmodified value. But it did not happen.

Eg.
export ENV_TEST_TIME=20:20

char* getTime (void)
{
char *pTime = getenv("ENV_TEST_TIME");
printf("\nEnv Time %s",pTime);
pTime[2]='\0';
return pTime;
}

int main(void)
{
printf("\nCall getTime %s",getTime());
printf("\nCall getTime %s",getTime());
return 0;
}
------------------------- output --------------
Env Time 20:20
Call getTime 20

Env Time 20
Call getTime 20

From the output, 'Env Time' value should be same for the both time of getTime function call but it differs. Hence, the getenv internally maps env variable to value and maintenance modified value until the application completes. So do not use env value directly to object manipulations.

No comments: