Reputation: 91
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.
Upvotes: 0
Views: 258
Reputation: 91
Oups my bad, I erased the "USERNAME=" part of the USERNAME tab, because loop started from 1 instead of 9...
Upvotes: 0
Reputation: 48672
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).
Upvotes: 2