My school wants me to implement the setenv()
standard c library function's behavior. I'm not allowed to use setenv()
for this implementation. How can I do that?
On many implementations of the C programming language and especially on POSIX, the environment is accessible from the environ
global variable. You may need to declare it manually as it's not declared in any standard header file:
extern char **environ;
environ
points to a NULL
terminated array of pointers to variable=value
strings. For example, if your environment has the variables foo
, bar
, and baz
, the entries in environ
might be:
environ[0] = "foo=a";
environ[1] = "bar=b";
environ[2] = "baz=c";
environ[3] = NULL;
To alter the environment without using the setenv()
or putenv()
functions, check if the key you want to set already exists. If it does, overwrite the entry for that key. Else you need to copy the content of environ
into a new array and add the new entry to its end. You can use malloc()
or calloc()
and memcpy()
for this purpose. Since this is homework, I'm not going to supply further details.
malloc()
and memcpy()
. Not that you can end up corrupting the environ
buffer. –
Differentiate © 2022 - 2024 — McMap. All rights reserved.