2

My school wants me to implement the setenv() standard library function's behavior. I'm not allowed to use setenv() for this implementation. How can I do that?

Iharob Al Asimi
  • 52,066
  • 5
  • 58
  • 95
Myranova
  • 113
  • 1
  • 10

1 Answers1

4

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.

fuz
  • 82,933
  • 24
  • 182
  • 332
  • Thanks a lot for this solution – Myranova Dec 15 '15 at 22:32
  • @FUZxxl I realized that this was the solution, but I also suspected that you would write it. – Iharob Al Asimi Dec 15 '15 at 22:33
  • @Myranova This is the acceptable answer because it's correct. Whether you try it and it works or not, depends on your skills with `malloc()` and `memcpy()`. Not that you can end up corrupting the `environ` buffer. – Iharob Al Asimi Dec 15 '15 at 22:34
  • 1
    @FUZxxl: adding a new string at the end will not always produce the expected behavior, the OP should first scan the strings to find a potential match for the environment variable whose value needs to be set and not copy this line into the new environment array. – chqrlie Dec 15 '15 at 22:38