#include #include #include extern char **environ; /* find the NULL pointer that indicates the end of the array v */ static int pos_null(char *v[]) { if (v == NULL) return -1; int i = 0; while (*v != NULL) { v++; i++; } return i; } static void print(void) { int n = pos_null(environ); int i; char **p; printf(" %08p = &environ, %d elements\n", &environ, n); for (p = environ, i = 0; *p != NULL; p++, i++) { printf(" %08p = &environ[%d] --> %08p --> \"%s\"\n", &environ[i], i, environ[i], environ[i]); } printf("\n"); } int main(int argc, char *argv[], char *envp[]) { char *a, *b, *c; printf("initial conditions\n"); print(); putenv("A=value_a"); putenv("B=value_b"); putenv("C=value_c"); printf("initial conditions\n"); print(); printf("proper use of getenv()\n"); a = getenv("A"); printf(" value of A at %08p is \"%s\"\n", a, a); b = getenv("B"); printf(" value of B at %08p is \"%s\"\n", b, b); c = getenv("C"); printf(" value of C at %08p is \"%s\"\n", c, c); printf("\n"); printf("this might be an improper use of getenv()\n"); a = getenv("A"); b = getenv("B"); c = getenv("C"); printf(" value of A at %08p is \"%s\"\n", a, a); printf(" value of B at %08p is \"%s\"\n", b, b); printf(" value of C at %08p is \"%s\"\n", c, c); printf("\n"); printf("this is not acceptable, but possibly not dangerous\n"); a = getenv("A"); /* The C Standard does not allow for direct changes to an environment * variable. The change via strcpy(a, "new_A") might actually work, * since the new string is shorter than the old string. However, * the GCC implementation of putenv() leaves a pointer to a string * constant, which is write-protected. Consequently we get a * Segmentation fault when attempting either of the following. */ strcpy(a, "new_A"); *a = 'x'; printf(" value of A at %08p is \"%s\"\n", a, a); printf(" value of B at %08p is \"%s\"\n", b, b); printf(" value of C at %08p is \"%s\"\n", c, c); printf("\n"); printf("this is not acceptable, and dangerous\n"); a = getenv("A"); strcpy(a, "very_long_replacement_for_the_value_of_A"); printf(" value of A at %08p is \"%s\"\n", a, a); printf(" value of B at %08p is \"%s\"\n", b, b); printf(" value of C at %08p is \"%s\"\n", c, c); printf("\n"); return 0; }