#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern char **environ;

int main(void)
{
    /*
       1. Remember the original environment memory.
    */
    char *old_start = environ[0];
    char *old_end = environ[0];

    for (int i = 0; environ[i] != NULL; i++) {
        char *end = environ[i] + strlen(environ[i]) + 1;

        if (environ[i] < old_start)
            old_start = environ[i];

        if (end > old_end)
            old_end = end;
    }

    size_t old_size = old_end - old_start;

    /*
       2. Copy every environment string.
       This is the sentence:
       "form a copy of the environment and put the corresponding
        addresses into the elements of the environ array"
    */
    for (int i = 0; environ[i] != NULL; i++) {
        environ[i] = strdup(environ[i]);
    }

    /*
       Now environ points to heap copies.
       The original environment memory is no longer needed by getenv().
    */

    char fake[] =
        "FAKE=123\0"
        "HELLO=world\0";

    if (sizeof(fake) > old_size) {
        fprintf(stderr, "Not enough space in original environment memory\n");
        return 1;
    }

    /*
       3. Overwrite the old original environment memory.
    */
    memset(old_start, 0, old_size);
    memcpy(old_start, fake, sizeof(fake));

    printf("PID: %d\n", getpid());

    printf("getenv(\"FAKE\") = %s\n", getenv("FAKE"));
    printf("getenv(\"PATH\") = %s\n", getenv("PATH"));

    getchar();

    return 0;
}
