0

I would like to display 2 environment variables that are passed as argument to another process using execve() function:

Main.c:

int main(){


    char USERNAME[10];
    strcpy(USERNAME, "USERNAME=");
    for (int i=1;i<10;i++){
        strcpy(USERNAME+i, "1");
    }

    char PATH[169];
    strcpy(PATH, "PATH=");
    for (int i=5;i<169;i++){
        strcpy(PATH+i, "A");
    }


    char * newargv[] = {"./get","", (char*)0};
    char * newenviron[] = {PATH,USERNAME};
    execve("./get", newargv, newenviron);
    return 0;
}

get.c:

int main()
{
    const char* s = getenv("PATH");
    printf("PATH :%s\n",s);
    const char* s2 = getenv("USERNAME");
    printf("USERNAME :%s\n",s2);
}

So I compile Main.c to Main and get.c to get, and execute Main, I get this output:

PATH :AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA USERNAME :(null)

I don't understand why USERNAME is NULL here.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
SdFRO0QS78
  • 91
  • 1
  • 2
  • 5
  • You could try doing `printf("<%s>\n", USERNAME);` inside the loop of your first program. You will see that it does not contain what you think. Or even better, learn how to use a debugger. – rodrigo Mar 05 '17 at 23:03
  • @WeatherVane Huh? `strcpy` is what initializes it. – Joseph Sible-Reinstate Monica Mar 05 '17 at 23:05
  • @JosephSible mybad, but still, the last `strcpy` in the loop will overrun the array, because of the terminating `'\0'`. – Weather Vane Mar 05 '17 at 23:10
  • Closely related to [Can't pass properly environment with `execve()` function](http://stackoverflow.com/questions/42635818/cant-pass-properly-environment-with-execve-function) by user [juRioqs75](http://stackoverflow.com/users/7457216/jurioqs75). – Jonathan Leffler Mar 06 '17 at 22:45

2 Answers2

2

You're missing a null terminator on the end of your newenviron array. Also, you're writing one more byte to each string than you've allocated space for (the ending \0 counts as a character).

0

Oups my bad, I erased the "USERNAME=" part of the USERNAME tab, because loop started from 1 instead of 9...

SdFRO0QS78
  • 91
  • 1
  • 2
  • 5