home *** CD-ROM | disk | FTP | other *** search
- /*
- * putenv.c - Replacement for broken putenv included in the BC++4.0 libraries
- *
- * Copyright (C) 1994 Troy Rollo.
- *
- * This file is explicitly placed in the public domain. It may be used for any purpose,
- * including, but not limited to, incorperation into commercial, shareware, freeware,
- * public domain or free software works, without fee of any kind being payable to
- * the author of this work, and without requirement for any credits or notice to be
- * attached to the work, provided this copyright notice remains intact, and provided
- * that if any changes are made, that a notice outlining the changes made be included
- * in this source code.
- *
- * This file is provided without any warranty of any kind, express or implied. The user
- * assumes all risks related to its use.
- */
-
- #include <string.h>
- #include <stdlib.h>
-
- extern char **_environ;
- extern unsigned _envSize;
- int
- putenv(char const *pchVar)
- {
- register char *pchEqual;
- register char **ppchEntry;
- char **ppchNewEnv;
- int nChars;
- int nNewSize;
-
- if (!pchVar || (pchEqual = strchr(pchVar, '=')) == 0)
- return -1;
- nChars = (int) (pchEqual - pchVar);
-
- /*
- * Note that the BC++4.0 library version also tests for
- * an empty string as a terminating condition. This should
- * not be necessary as _setenv replaces the pointer to
- * the empty string with a NULL pointer.
- */
- for (ppchEntry = _environ;
- *ppchEntry;
- ppchEntry++)
- {
- if (!strncmp(*ppchEntry, pchVar, nChars + 1))
- {
- if (!pchEqual[1])
- {
- while ((ppchEntry[0] = ppchEntry[1]) != 0)
- ppchEntry++;
- }
- else
- {
- *ppchEntry = (char *) pchVar;
- }
- return 0;
- }
- }
- if (!pchEqual[1])
- return 0;
-
- /*
- * Why the -1 here? If we don't do this, we might be overwriting
- * the terminating NULL pointer when there is memory after it that may
- * be uninitialised and/or belong to something else. Then we have the
- * potential to walk off the end of the array.
- */
- if (ppchEntry - _environ > (_envSize / 4) - 1)
- {
- nNewSize = _envSize + sizeof(char *) * 4;
- ppchNewEnv = (char **) malloc(nNewSize);
- memcpy(ppchNewEnv, _environ, _envSize);
- free(_environ);
- ppchEntry = ppchNewEnv + (ppchEntry - _environ);
- _environ = ppchNewEnv;
- _envSize = nNewSize;
- }
-
- ppchEntry[0] = (char *) pchVar;
- ppchEntry[1] = 0;
- return 0;
- }